<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.9.2" />
<title>ascend API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<link rel="preconnect" href="https://www.google.com">
<script async src="https://cse.google.com/cse.js?cx=017837193012385208679:pey8ky8gdqw"></script>
<style>
.gsc-control-cse {padding:0 !important;margin-top:1em}
body.gsc-overflow-hidden #sidebar {overflow: visible;}
</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
<style>.homelink{display:block;font-size:2em;font-weight:bold;color:#555;padding-bottom:.5em;border-bottom:1px solid silver}.homelink:hover{color:inherit}.homelink img{max-width:20%;max-height:5em;margin:auto;margin-bottom:.3em}</style>
<link rel="canonical" href="https://bazige.github.io/ascend/">
<link rel="icon" href="https://bazige.github.io/ascend/logo/logo.png"">
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Package <code>ascend</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/__init__.py#L0-L37" class="git-link">Browse git</a>
</summary>
<pre><code class="python"># -*- coding: utf-8 -*-

from .common import *
from .resource import *
from .data import *
from .image import *
from .model.model import AscendModel

from .video import *
from .profiling.profiling import Profiling

from .ops import *
from .post_process import *

__all__ = [
    &#39;Log&#39;, &#39;show_growth&#39;, &#39;is_filepath&#39;, &#39;check_file_exist&#39;, &#39;mkdir_or_exist&#39;,

    &#39;AscendArray&#39;, &#39;imgs2tensor&#39;, &#39;tensor2imgs&#39;,

    &#39;rgb2ycbcr&#39;, &#39;bgr2ycbcr&#39;, &#39;ycbcr2rgb&#39;, &#39;ycbcr2bgr&#39;,
    &#39;show_img&#39;, &#39;show_bbox&#39;, &#39;show_tensor&#39;, 

    &#39;Image&#39;, &#39;AscendModel&#39;, &#39;Profiling&#39;,

    &#39;Matmul&#39;, &#39;Vmul&#39;, &#39;Cast&#39;, &#39;ArgMax&#39;, &#39;Transpose&#39;, &#39;Permute&#39;,

    &#39;Context&#39;, &#39;Memory&#39;, &#39;bind_context&#39;, &#39;create_stream&#39;,
    &#39;acl_vesion&#39;, &#39;run_mode&#39;, &#39;device_num&#39;, 

    &#39;bbox_overlaps&#39;, &#39;wider_face_classes&#39;, &#39;voc_classes&#39;, &#39;imagenet_det_classes&#39;,
    &#39;imagenet_vid_classes&#39;, &#39;coco_classes&#39;, &#39;cityscapes_classes&#39;, &#39;get_classes&#39;, 
    &#39;Color&#39;, &#39;color_val&#39;, &#39;nms&#39;, &#39;color_gen&#39;,
    &#39;imshow&#39;, &#39;imshow_bboxes&#39;, &#39;imshow_det_bboxes&#39;, &#39;imshow_bboxes_colors&#39;, 
    &#39;draw_bboxes&#39;,
    &#39;Vdec&#39;, &#39;VideoCapture&#39;, &#39;Venc&#39;, &#39;VideoWriter&#39;,
]</code></pre>
</details>
</section>
<section>
<h2 class="section-title" id="header-submodules">Sub-modules</h2>
<dl>
<dt><code class="name"><a title="ascend.common" href="common/index.html">ascend.common</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.data" href="data/index.html">ascend.data</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.image" href="image/index.html">ascend.image</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.model" href="model/index.html">ascend.model</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.ops" href="ops/index.html">ascend.ops</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.post_process" href="post_process/index.html">ascend.post_process</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.profiling" href="profiling/index.html">ascend.profiling</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.resource" href="resource/index.html">ascend.resource</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt><code class="name"><a title="ascend.video" href="video/index.html">ascend.video</a></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="ascend.acl_vesion"><code class="name flex">
<span>def <span class="ident">acl_vesion</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>get acl version of system intalled. </p>
<h2 id="returns">Returns</h2>
<p>version (str): vesion = major_ver + minor_ver + path_ver, while major_ver is
major version, minor_ver is the minor verson and path_ver is patch version
Typical usage example:</p>
<pre><code class="language-python">version = ascend.acl_vesion()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L21-L38" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def acl_vesion(self):
    &#34;&#34;&#34; get acl version of system intalled. 

    Returns:
        version (str): vesion = major_ver + minor_ver + path_ver, while major_ver is 
            major version, minor_ver is the minor verson and path_ver is patch version

    Typical usage example:
    ```python
    version = ascend.acl_vesion()
    ```   
    &#34;&#34;&#34;
    major_ver, minor_ver, patch_ver, ret = acl.get_version()
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;pyACL is not installed or invalid.&#34;)

    version = str(major_ver) + &#39;.&#39; + str(minor_ver) + &#39;.&#39; + str(patch_ver)
    return version</code></pre>
</details>
</dd>
<dt id="ascend.bbox_overlaps"><code class="name flex">
<span>def <span class="ident">bbox_overlaps</span></span>(<span>bboxes1, bboxes2, mode='iou', eps=1e-06)</span>
</code></dt>
<dd>
<div class="desc"><p>Calculate the ious between each bbox of bboxes1 and bboxes2.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>bboxes1</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Input bboxes1 with shape (n, 4)</dd>
<dt><strong><code>bboxes2</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Input bboxes2 with shape (k, 4)</dd>
<dt><strong><code>mode</code></strong> :&ensp;<code>str</code></dt>
<dd>Iou (intersection over union) or iof (intersection
over foreground)</dd>
<dt><strong><code>eps</code></strong> :&ensp;<code>float</code>, optional</dt>
<dd>The adjusted parameter. Defaults to 1e-6.</dd>
</dl>
<h2 id="returns">Returns</h2>
<p>ious (ndarray): The result with shape (n, k)</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/bbox_overlaps.py#L4-L56" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def bbox_overlaps(bboxes1, bboxes2, mode=&#39;iou&#39;, eps=1e-6):
    &#34;&#34;&#34;Calculate the ious between each bbox of bboxes1 and bboxes2.

    Args:
        bboxes1 (ndarray): Input bboxes1 with shape (n, 4)
        bboxes2 (ndarray): Input bboxes2 with shape (k, 4)
        mode (str): Iou (intersection over union) or iof (intersection
            over foreground)
        eps (float, optional): The adjusted parameter. Defaults to 1e-6.

    Returns:
        ious (ndarray): The result with shape (n, k)
    &#34;&#34;&#34;
    if not isinstance(bboxes1, np.ndarray):
        raise TypeError(f&#34;Input bboxes1 expects a np.ndrray, but got {type(bboxes1)}.&#34;)
    if not isinstance(bboxes2, np.ndarray):
        raise TypeError(f&#34;Input bboxes2 expects a np.ndrray, but got {type(bboxes2)}.&#34;)

    assert mode in [&#39;iou&#39;, &#39;iof&#39;]

    bboxes1 = bboxes1.astype(np.float32)
    bboxes2 = bboxes2.astype(np.float32)
    rows = bboxes1.shape[0]
    cols = bboxes2.shape[0]
    ious = np.zeros((rows, cols), dtype=np.float32)
    if rows * cols == 0:
        return ious
        
    exchange = False
    if bboxes1.shape[0] &gt; bboxes2.shape[0]:
        bboxes1, bboxes2 = bboxes2, bboxes1
        ious = np.zeros((cols, rows), dtype=np.float32)
        exchange = True

    area1 = (bboxes1[:, 2] - bboxes1[:, 0]) * (bboxes1[:, 3] - bboxes1[:, 1])
    area2 = (bboxes2[:, 2] - bboxes2[:, 0]) * (bboxes2[:, 3] - bboxes2[:, 1])

    for i in range(bboxes1.shape[0]):
        x_start = np.maximum(bboxes1[i, 0], bboxes2[:, 0])
        y_start = np.maximum(bboxes1[i, 1], bboxes2[:, 1])
        x_end = np.minimum(bboxes1[i, 2], bboxes2[:, 2])
        y_end = np.minimum(bboxes1[i, 3], bboxes2[:, 3])
        overlap = np.maximum(x_end - x_start, 0) * np.maximum(
            y_end - y_start, 0)
        if mode == &#39;iou&#39;:
            union = area1[i] + area2 - overlap
        else:
            union = area1[i] if not exchange else area2
        union = np.maximum(union, eps)
        ious[i, :] = overlap / union
    if exchange:
        ious = ious.T
    return ious</code></pre>
</details>
</dd>
<dt id="ascend.bgr2ycbcr"><code class="name flex">
<span>def <span class="ident">bgr2ycbcr</span></span>(<span>img, y_only=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert a BGR image to YCbCr image.</p>
<p>The bgr version of rgb2ycbcr.
It implements the ITU-R BT.601 conversion for standard-definition
television. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.">https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.</a></p>
<p>It differs from a similar function in cv2.cvtColor: <code>BGR &lt;-&gt; YCrCb</code>.
In OpenCV, it implements a JPEG conversion. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.">https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.</a></p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>The input image. It accepts:</dd>
</dl>
<ul>
<li>np.uint8 type with range [0, 255].</li>
<li>np.float16 type with range [0, 1].</li>
</ul>
<dl>
<dt><strong><code>y_only</code></strong> :&ensp;<code>bool</code></dt>
<dd>Whether to only return Y channel. Default: False.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The converted YCbCr image. The output image has the same type
and range as input image.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/colorspace.py#L123-L169" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def bgr2ycbcr(img, y_only=False):
    &#34;&#34;&#34;Convert a BGR image to YCbCr image.

    The bgr version of rgb2ycbcr.
    It implements the ITU-R BT.601 conversion for standard-definition
    television. See more details in
    https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.

    It differs from a similar function in cv2.cvtColor: `BGR &lt;-&gt; YCrCb`.
    In OpenCV, it implements a JPEG conversion. See more details in
    https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.

    Args:
        img (ndarray): The input image. It accepts:

        - np.uint8 type with range [0, 255].
        - np.float16 type with range [0, 1].

        y_only (bool): Whether to only return Y channel. Default: False.

    Returns:
        ndarray: The converted YCbCr image. The output image has the same type
            and range as input image.
    &#34;&#34;&#34;
    img_type = img.dtype
    img = _convert_input_type_range(img)
    if y_only:
        # out_img = np.dot(img, [24.966, 128.553, 65.481]) + 16.0
        trans = np.array([24.966, 128.553, 65.481], dtype=np.float16)
        bias = np.array([16.0], dtype=np.float16)
    else:
        trans = np.array([[ 24.966,   112.0, -18.214], 
                          [128.553, -74.203, -93.786],
                          [ 65.481, -37.797,   112.0]], dtype=np.float16)
        bias = np.array([16, 128, 128], dtype=np.float16)

    # clone to device
    trans = AscendArray.clone(trans)
    bias = AscendArray.clone(bias)

    if y_only:
        out_inst = Vmul(img, trans, bias)
    else:
         # do transmit
        out_inst = Matmul(img, trans, bias)
    out_img = _convert_output_type_range(out_inst.out, img_type)
    return out_img</code></pre>
</details>
</dd>
<dt id="ascend.bind_context"><code class="name flex">
<span>def <span class="ident">bind_context</span></span>(<span>context)</span>
</code></dt>
<dd>
<div class="desc"><p>Binding an existing context. If context is not exist, raise an error else set this context.</p>
<h2 id="args">Args</h2>
<p>context.</p>
<h2 id="returns">Returns</h2>
<p>None.
Typical usage example:</p>
<pre><code class="language-python">ascend.bind_context(context)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L118-L140" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def bind_context(context):
    &#34;&#34;&#34; Binding an existing context. If context is not exist, raise an error else set this context.
    Args:
        context.

    Returns:
        None.
    
    Typical usage example:
    ```python
    ascend.bind_context(context)
    ```
    &#34;&#34;&#34;
    if context is None:
        context, ret = acl.rt.get_context()
        assert ret == ACL_SUCCESS, f&#34;get context failed in bind_context, return {ret}.&#34;
    
    ret = acl.rt.set_context(context)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;acl set context failed in bind_context,, return {ret}.&#34;)

    Log(INFO, f&#34;Set context {context} success.&#34;)
    return ret</code></pre>
</details>
</dd>
<dt id="ascend.check_file_exist"><code class="name flex">
<span>def <span class="ident">check_file_exist</span></span>(<span>filename, msg_tmpl="file '{}' does not exist")</span>
</code></dt>
<dd>
<div class="desc"><p>Check specific file is exist</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>filename</code></strong> :&ensp;<code>str</code></dt>
<dd>Input file name </dd>
<dt><strong><code>msg_tmpl</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>raise message. Defaults to "file '{}' does not exist".</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/common/path.py#L56-L64" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def check_file_exist(filename, msg_tmpl=&#34;file &#39;{}&#39; does not exist&#34;):
    &#34;&#34;&#34;Check specific file is exist

    Args:
        filename (str): Input file name 
        msg_tmpl (str, optional): raise message. Defaults to &#34;file &#39;{}&#39; does not exist&#34;.
    &#34;&#34;&#34;    
    if not osp.isfile(filename):
        raise FileNotFoundError(msg_tmpl.format(filename))</code></pre>
</details>
</dd>
<dt id="ascend.cityscapes_classes"><code class="name flex">
<span>def <span class="ident">cityscapes_classes</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Cityscapes dataset classes</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>Cityscapes dataset classes</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L108-L117" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def cityscapes_classes():
    &#34;&#34;&#34;Cityscapes dataset classes

    Returns:
        list: Cityscapes dataset classes
    &#34;&#34;&#34;    
    return [
        &#39;person&#39;, &#39;rider&#39;, &#39;car&#39;, &#39;truck&#39;, &#39;bus&#39;, &#39;train&#39;, &#39;motorcycle&#39;,
        &#39;bicycle&#39;
    ]</code></pre>
</details>
</dd>
<dt id="ascend.coco_classes"><code class="name flex">
<span>def <span class="ident">coco_classes</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>COCO dataset classes</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>COCO dataset classes</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L85-L105" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def coco_classes():
    &#34;&#34;&#34;COCO dataset classes

    Returns:
        list: COCO dataset classes
    &#34;&#34;&#34;    
    return [
        &#39;person&#39;, &#39;bicycle&#39;, &#39;car&#39;, &#39;motorcycle&#39;, &#39;airplane&#39;, &#39;bus&#39;, &#39;train&#39;,
        &#39;truck&#39;, &#39;boat&#39;, &#39;traffic_light&#39;, &#39;fire_hydrant&#39;, &#39;stop_sign&#39;,
        &#39;parking_meter&#39;, &#39;bench&#39;, &#39;bird&#39;, &#39;cat&#39;, &#39;dog&#39;, &#39;horse&#39;, &#39;sheep&#39;,
        &#39;cow&#39;, &#39;elephant&#39;, &#39;bear&#39;, &#39;zebra&#39;, &#39;giraffe&#39;, &#39;backpack&#39;, &#39;umbrella&#39;,
        &#39;handbag&#39;, &#39;tie&#39;, &#39;suitcase&#39;, &#39;frisbee&#39;, &#39;skis&#39;, &#39;snowboard&#39;,
        &#39;sports_ball&#39;, &#39;kite&#39;, &#39;baseball_bat&#39;, &#39;baseball_glove&#39;, &#39;skateboard&#39;,
        &#39;surfboard&#39;, &#39;tennis_racket&#39;, &#39;bottle&#39;, &#39;wine_glass&#39;, &#39;cup&#39;, &#39;fork&#39;,
        &#39;knife&#39;, &#39;spoon&#39;, &#39;bowl&#39;, &#39;banana&#39;, &#39;apple&#39;, &#39;sandwich&#39;, &#39;orange&#39;,
        &#39;broccoli&#39;, &#39;carrot&#39;, &#39;hot_dog&#39;, &#39;pizza&#39;, &#39;donut&#39;, &#39;cake&#39;, &#39;chair&#39;,
        &#39;couch&#39;, &#39;potted_plant&#39;, &#39;bed&#39;, &#39;dining_table&#39;, &#39;toilet&#39;, &#39;tv&#39;,
        &#39;laptop&#39;, &#39;mouse&#39;, &#39;remote&#39;, &#39;keyboard&#39;, &#39;cell_phone&#39;, &#39;microwave&#39;,
        &#39;oven&#39;, &#39;toaster&#39;, &#39;sink&#39;, &#39;refrigerator&#39;, &#39;book&#39;, &#39;clock&#39;, &#39;vase&#39;,
        &#39;scissors&#39;, &#39;teddy_bear&#39;, &#39;hair_drier&#39;, &#39;toothbrush&#39;
    ]</code></pre>
</details>
</dd>
<dt id="ascend.color_gen"><code class="name flex">
<span>def <span class="ident">color_gen</span></span>(<span>class_num)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert various input to color tuples.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>class_num</code></strong> :&ensp;<code>int</code></dt>
<dd>Class numbers</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list[int]</code></dt>
<dd>Generate colors according to class number.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/color.py#L53-L67" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def color_gen(class_num):
    &#34;&#34;&#34;Convert various input to color tuples.

    Args:
        class_num (int): Class numbers

    Returns:
        list[int]: Generate colors according to class number.
    &#34;&#34;&#34;
    assert class_num &gt;= 0, f&#34;Input class_num should be larger than 0.&#34;
    gen_color = []
    for _ in range(class_num):
        color = np.random.randint(0, 255, size=3).tolist()
        gen_color.append(color)
    return gen_color</code></pre>
</details>
</dd>
<dt id="ascend.color_val"><code class="name flex">
<span>def <span class="ident">color_val</span></span>(<span>color)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert various input to color tuples.</p>
<h2 id="args">Args</h2>
<p>color (<code><a title="ascend.Color" href="#ascend.Color">Color</a></code>/str/tuple/int/ndarray): Color inputs</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>tuple[int]</code></dt>
<dd>A tuple of 3 integers indicating BGR channels.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/color.py#L24-L51" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def color_val(color):
    &#34;&#34;&#34;Convert various input to color tuples.

    Args:
        color (`Color`/str/tuple/int/ndarray): Color inputs

    Returns:
        tuple[int]: A tuple of 3 integers indicating BGR channels.
    &#34;&#34;&#34;
    if is_str(color):
        return Color[color].value
    elif isinstance(color, Color):
        return color.value
    elif isinstance(color, tuple):
        assert len(color) == 3
        for channel in color:
            assert 0 &lt;= channel &lt;= 255
        return color
    elif isinstance(color, int):
        assert 0 &lt;= color &lt;= 255
        return color, color, color
    elif isinstance(color, np.ndarray):
        assert color.ndim == 1 and color.size == 3
        assert np.all((color &gt;= 0) &amp; (color &lt;= 255))
        color = color.astype(np.uint8)
        return tuple(color)
    else:
        raise TypeError(f&#39;Invalid type for color: {type(color)}&#39;)</code></pre>
</details>
</dd>
<dt id="ascend.create_stream"><code class="name flex">
<span>def <span class="ident">create_stream</span></span>(<span>context=None, stream=None)</span>
</code></dt>
<dd>
<div class="desc"><p>create a stream. </p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>case 1. stream is not None, return stream.
case 2. stream and context are None. Get the context and create a new stream.
case 3. stream is None and context is not None. Create a new stream on existing context.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code></dt>
<dd>If context is None, it will get context and then create a stream.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[int]</code></dt>
<dd>The created stream or original</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L85-L115" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def create_stream(context=None, stream=None):
    &#34;&#34;&#34; create a stream. 

    .. note::
       case 1. stream is not None, return stream.
       case 2. stream and context are None. Get the context and create a new stream.
       case 3. stream is None and context is not None. Create a new stream on existing context.

    Args:
        context (int): If context is None, it will get context and then create a stream.

    Returns:
        [int]: The created stream or original
    &#34;&#34;&#34;
    if stream:
        return stream

    if context is None:
        context, ret = acl.rt.get_context()
        assert ret == ACL_SUCCESS, f&#34;get context failed in bind_stream, return {ret}.&#34;

    ret = acl.rt.set_context(context)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;acl set context failed, return {ret}.&#34;)

    stream, ret = acl.rt.create_stream()
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;create stream failed in create_stream, return {ret}.&#34;)
    
    Log(INFO, f&#34;Create stream at context {context} success.&#34;)
    return stream</code></pre>
</details>
</dd>
<dt id="ascend.device_num"><code class="name flex">
<span>def <span class="ident">device_num</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Get device number of the system</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[int]</code></dt>
<dd>The available number of device.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">dev_num = ascend.device_num()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L64-L82" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def device_num():
    &#34;&#34;&#34;Get device number of the system

    Args:
        None

    Returns:
        [int]: The available number of device.

    Typical usage example:
    ```python
    dev_num = ascend.device_num()
    ```
    &#34;&#34;&#34;
    count, ret = acl.rt.get_device_count()
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;pyACL is not installed or Atlas device is not working well.&#34;)

    return count</code></pre>
</details>
</dd>
<dt id="ascend.draw_bboxes"><code class="name flex">
<span>def <span class="ident">draw_bboxes</span></span>(<span>img, bboxes, class_names, thickness=1, font_scale=0.5, show=True, win_name='', wait_time=0, out_file=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Draw bboxes and class labels (with scores) on an image with colors.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>, ndarray</code></dt>
<dd>The image to be displayed.</dd>
<dt><strong><code>bboxes</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Bounding boxes (with scores, label), shaped (n, 5) or (n, 6).
shape like [x1, y1, x2, y2, scores, classid] or [x1, y1, x2, y2, classid]</dd>
<dt><strong><code>class_names</code></strong> :&ensp;<code>list[str]</code></dt>
<dd>Names of each classes.</dd>
<dt><strong><code>thickness</code></strong> :&ensp;<code>int</code></dt>
<dd>Thickness of lines.</dd>
<dt><strong><code>font_scale</code></strong> :&ensp;<code>float</code></dt>
<dd>Font scales of texts.</dd>
<dt><strong><code>show</code></strong> :&ensp;<code>bool</code></dt>
<dd>Whether to show the image.</dd>
<dt><strong><code>win_name</code></strong> :&ensp;<code>str</code></dt>
<dd>The window name.</dd>
<dt><strong><code>wait_time</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of waitKey param.</dd>
<dt><strong><code>out_file</code></strong> :&ensp;<code>str</code> or <code>None</code></dt>
<dd>The filename to write the image.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The image with bboxes drawn on it.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/image.py#L239-L293" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def draw_bboxes(img,
                bboxes,
                class_names,
                thickness=1,
                font_scale=0.5,
                show=True,
                win_name=&#39;&#39;,
                wait_time=0,
                out_file=None):
    &#34;&#34;&#34;Draw bboxes and class labels (with scores) on an image with colors.

    Args:
        img (AscendArray, ndarray): The image to be displayed.
        bboxes (ndarray): Bounding boxes (with scores, label), shaped (n, 5) or (n, 6).
            shape like [x1, y1, x2, y2, scores, classid] or [x1, y1, x2, y2, classid]

        class_names (list[str]): Names of each classes.
        thickness (int): Thickness of lines.
        font_scale (float): Font scales of texts.
        show (bool): Whether to show the image.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
        out_file (str or None): The filename to write the image.

    Returns:
        ndarray: The image with bboxes drawn on it.
    &#34;&#34;&#34;
    assert bboxes.ndim == 2
    assert bboxes.shape[1] == 5 or bboxes.shape[1] == 6
    img = trans_numpy(img)

    img = np.ascontiguousarray(img).astype(np.uint8)  # 可能传入的不是uint8
    font = cv2.FONT_HERSHEY_DUPLEX

    for bbox, label in zip(bboxes[:,:5], bboxes[:,-1].astype(&#39;int32&#39;)):
        bbox_int = bbox.astype(np.int32)
        left_top = (bbox_int[0], bbox_int[1])
        right_bottom = (bbox_int[2], bbox_int[3])
        color = COLORS_81[label%80 + 1].tolist()
        cv2.rectangle(img, left_top, right_bottom, color, thickness)
        label_text = class_names[label] if class_names is not None else f&#39;cls {label}&#39;

        if len(bbox) &gt; 4:
            label_text += f&#39;:{bbox[-1]:.02f}&#39;

        text_w, text_h = cv2.getTextSize(label_text, font, font_scale, thickness)[0]
        cv2.rectangle(img, left_top, (bbox_int[0] + text_w, bbox_int[1] + text_h + 5), color, -1)
        cv2.putText(img, label_text, (bbox_int[0], bbox_int[1] + 15),
                    font, font_scale, (255, 255, 255), thickness, cv2.LINE_AA)

    if show:
        imshow(img, win_name, wait_time)
    if out_file is not None:
        cv2.imwrite(out_file, img)
    return img</code></pre>
</details>
</dd>
<dt id="ascend.get_classes"><code class="name flex">
<span>def <span class="ident">get_classes</span></span>(<span>dataset)</span>
</code></dt>
<dd>
<div class="desc"><p>Get class names of a dataset.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>dataset</code></strong> :&ensp;<code>str</code></dt>
<dd>Input dataset's name</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>The specific dataset classes</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L130-L151" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def get_classes(dataset):
    &#34;&#34;&#34;Get class names of a dataset.

    Args:
        dataset (str): Input dataset&#39;s name

    Returns:
        list: The specific dataset classes
    &#34;&#34;&#34;    
    alias2name = {}
    for name, aliases in dataset_aliases.items():
        for alias in aliases:
            alias2name[alias] = name

    if isinstance(dataset, str):
        if dataset in alias2name:
            labels = eval(alias2name[dataset] + &#39;_classes()&#39;)
        else:
            raise ValueError(f&#39;Unrecognized dataset: {dataset}&#39;)
    else:
        raise TypeError(f&#39;dataset must a str, but got {type(dataset)}&#39;)
    return labels</code></pre>
</details>
</dd>
<dt id="ascend.imagenet_det_classes"><code class="name flex">
<span>def <span class="ident">imagenet_det_classes</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Imagenet detection classes</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>Imagenet classes</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L24-L67" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imagenet_det_classes():
    &#34;&#34;&#34;Imagenet detection classes

    Returns:
        list: Imagenet classes
    &#34;&#34;&#34;    
    return [
        &#39;accordion&#39;, &#39;airplane&#39;, &#39;ant&#39;, &#39;antelope&#39;, &#39;apple&#39;, &#39;armadillo&#39;,
        &#39;artichoke&#39;, &#39;axe&#39;, &#39;baby_bed&#39;, &#39;backpack&#39;, &#39;bagel&#39;, &#39;balance_beam&#39;,
        &#39;banana&#39;, &#39;band_aid&#39;, &#39;banjo&#39;, &#39;baseball&#39;, &#39;basketball&#39;, &#39;bathing_cap&#39;,
        &#39;beaker&#39;, &#39;bear&#39;, &#39;bee&#39;, &#39;bell_pepper&#39;, &#39;bench&#39;, &#39;bicycle&#39;, &#39;binder&#39;,
        &#39;bird&#39;, &#39;bookshelf&#39;, &#39;bow_tie&#39;, &#39;bow&#39;, &#39;bowl&#39;, &#39;brassiere&#39;, &#39;burrito&#39;,
        &#39;bus&#39;, &#39;butterfly&#39;, &#39;camel&#39;, &#39;can_opener&#39;, &#39;car&#39;, &#39;cart&#39;, &#39;cattle&#39;,
        &#39;cello&#39;, &#39;centipede&#39;, &#39;chain_saw&#39;, &#39;chair&#39;, &#39;chime&#39;, &#39;cocktail_shaker&#39;,
        &#39;coffee_maker&#39;, &#39;computer_keyboard&#39;, &#39;computer_mouse&#39;, &#39;corkscrew&#39;,
        &#39;cream&#39;, &#39;croquet_ball&#39;, &#39;crutch&#39;, &#39;cucumber&#39;, &#39;cup_or_mug&#39;, &#39;diaper&#39;,
        &#39;digital_clock&#39;, &#39;dishwasher&#39;, &#39;dog&#39;, &#39;domestic_cat&#39;, &#39;dragonfly&#39;,
        &#39;drum&#39;, &#39;dumbbell&#39;, &#39;electric_fan&#39;, &#39;elephant&#39;, &#39;face_powder&#39;, &#39;fig&#39;,
        &#39;filing_cabinet&#39;, &#39;flower_pot&#39;, &#39;flute&#39;, &#39;fox&#39;, &#39;french_horn&#39;, &#39;frog&#39;,
        &#39;frying_pan&#39;, &#39;giant_panda&#39;, &#39;goldfish&#39;, &#39;golf_ball&#39;, &#39;golfcart&#39;,
        &#39;guacamole&#39;, &#39;guitar&#39;, &#39;hair_dryer&#39;, &#39;hair_spray&#39;, &#39;hamburger&#39;,
        &#39;hammer&#39;, &#39;hamster&#39;, &#39;harmonica&#39;, &#39;harp&#39;, &#39;hat_with_a_wide_brim&#39;,
        &#39;head_cabbage&#39;, &#39;helmet&#39;, &#39;hippopotamus&#39;, &#39;horizontal_bar&#39;, &#39;horse&#39;,
        &#39;hotdog&#39;, &#39;iPod&#39;, &#39;isopod&#39;, &#39;jellyfish&#39;, &#39;koala_bear&#39;, &#39;ladle&#39;,
        &#39;ladybug&#39;, &#39;lamp&#39;, &#39;laptop&#39;, &#39;lemon&#39;, &#39;lion&#39;, &#39;lipstick&#39;, &#39;lizard&#39;,
        &#39;lobster&#39;, &#39;maillot&#39;, &#39;maraca&#39;, &#39;microphone&#39;, &#39;microwave&#39;, &#39;milk_can&#39;,
        &#39;miniskirt&#39;, &#39;monkey&#39;, &#39;motorcycle&#39;, &#39;mushroom&#39;, &#39;nail&#39;, &#39;neck_brace&#39;,
        &#39;oboe&#39;, &#39;orange&#39;, &#39;otter&#39;, &#39;pencil_box&#39;, &#39;pencil_sharpener&#39;, &#39;perfume&#39;,
        &#39;person&#39;, &#39;piano&#39;, &#39;pineapple&#39;, &#39;ping-pong_ball&#39;, &#39;pitcher&#39;, &#39;pizza&#39;,
        &#39;plastic_bag&#39;, &#39;plate_rack&#39;, &#39;pomegranate&#39;, &#39;popsicle&#39;, &#39;porcupine&#39;,
        &#39;power_drill&#39;, &#39;pretzel&#39;, &#39;printer&#39;, &#39;puck&#39;, &#39;punching_bag&#39;, &#39;purse&#39;,
        &#39;rabbit&#39;, &#39;racket&#39;, &#39;ray&#39;, &#39;red_panda&#39;, &#39;refrigerator&#39;,
        &#39;remote_control&#39;, &#39;rubber_eraser&#39;, &#39;rugby_ball&#39;, &#39;ruler&#39;,
        &#39;salt_or_pepper_shaker&#39;, &#39;saxophone&#39;, &#39;scorpion&#39;, &#39;screwdriver&#39;,
        &#39;seal&#39;, &#39;sheep&#39;, &#39;ski&#39;, &#39;skunk&#39;, &#39;snail&#39;, &#39;snake&#39;, &#39;snowmobile&#39;,
        &#39;snowplow&#39;, &#39;soap_dispenser&#39;, &#39;soccer_ball&#39;, &#39;sofa&#39;, &#39;spatula&#39;,
        &#39;squirrel&#39;, &#39;starfish&#39;, &#39;stethoscope&#39;, &#39;stove&#39;, &#39;strainer&#39;,
        &#39;strawberry&#39;, &#39;stretcher&#39;, &#39;sunglasses&#39;, &#39;swimming_trunks&#39;, &#39;swine&#39;,
        &#39;syringe&#39;, &#39;table&#39;, &#39;tape_player&#39;, &#39;tennis_ball&#39;, &#39;tick&#39;, &#39;tie&#39;,
        &#39;tiger&#39;, &#39;toaster&#39;, &#39;traffic_light&#39;, &#39;train&#39;, &#39;trombone&#39;, &#39;trumpet&#39;,
        &#39;turtle&#39;, &#39;tv_or_monitor&#39;, &#39;unicycle&#39;, &#39;vacuum&#39;, &#39;violin&#39;,
        &#39;volleyball&#39;, &#39;waffle_iron&#39;, &#39;washer&#39;, &#39;water_bottle&#39;, &#39;watercraft&#39;,
        &#39;whale&#39;, &#39;wine_bottle&#39;, &#39;zebra&#39;
    ]</code></pre>
</details>
</dd>
<dt id="ascend.imagenet_vid_classes"><code class="name flex">
<span>def <span class="ident">imagenet_vid_classes</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Imagenet validation classes</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>Imagenet validation classes</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L70-L82" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imagenet_vid_classes():
    &#34;&#34;&#34;Imagenet validation classes

    Returns:
        list: Imagenet validation classes
    &#34;&#34;&#34;    
    return [
        &#39;airplane&#39;, &#39;antelope&#39;, &#39;bear&#39;, &#39;bicycle&#39;, &#39;bird&#39;, &#39;bus&#39;, &#39;car&#39;,
        &#39;cattle&#39;, &#39;dog&#39;, &#39;domestic_cat&#39;, &#39;elephant&#39;, &#39;fox&#39;, &#39;giant_panda&#39;,
        &#39;hamster&#39;, &#39;horse&#39;, &#39;lion&#39;, &#39;lizard&#39;, &#39;monkey&#39;, &#39;motorcycle&#39;, &#39;rabbit&#39;,
        &#39;red_panda&#39;, &#39;sheep&#39;, &#39;snake&#39;, &#39;squirrel&#39;, &#39;tiger&#39;, &#39;train&#39;, &#39;turtle&#39;,
        &#39;watercraft&#39;, &#39;whale&#39;, &#39;zebra&#39;
    ]</code></pre>
</details>
</dd>
<dt id="ascend.imgs2tensor"><code class="name flex">
<span>def <span class="ident">imgs2tensor</span></span>(<span>imgs, tensor_fmt='NCHW', tensor_ptr=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert 3-channel images to tensor</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>imgs</code></strong> :&ensp;<code>list[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code></dt>
<dd>A list that contains multiple images,
shape (h, w, c), support RGB/BGR, YUV444</dd>
<dt><strong><code>tensor_fmt</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Data format of output tensor. Defaults to 'NCHW'.</dd>
<dt><strong><code>tensor_ptr</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Data pointer of output tensor. If it is None,
we will create an AscendArray and bind the array's data pointer to it.
Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Tensor that contains multiple images, shape (N, C, H, W)
or shape (N, H, W, C)</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">imgs = [ascend_array1, ascend_array2]
data = ascend.imgs2tensor(imgs, tensor_fmt='NHWC')
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/tensor.py#L38-L106" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imgs2tensor(imgs, tensor_fmt=&#39;NCHW&#39;, tensor_ptr=None):
    &#34;&#34;&#34;Convert 3-channel images to tensor

    Args:
        imgs (list[AscendArray]): A list that contains multiple images,
            shape (h, w, c), support RGB/BGR, YUV444
        tensor_fmt (str, optional): Data format of output tensor. Defaults to &#39;NCHW&#39;.
        tensor_ptr (int, optional): Data pointer of output tensor. If it is None, 
            we will create an AscendArray and bind the array&#39;s data pointer to it. 
            Defaults to None.

    Returns:
        AscendArray: Tensor that contains multiple images, shape (N, C, H, W) 
            or shape (N, H, W, C)

    Typical usage example:
    ```python
    imgs = [ascend_array1, ascend_array2]
    data = ascend.imgs2tensor(imgs, tensor_fmt=&#39;NHWC&#39;)
    ```
    &#34;&#34;&#34;
    if not isinstance(imgs, list):
        raise TypeError(f&#34;Input imgs expects a list, but got {type(imgs)}.&#34;)

    if len(imgs) &lt;= 0:
        raise ValueError(f&#34;Input imgs is a null list.&#34;)

    # get first image&#39;s shape and format
    format = imgs[0].format
    _shape = imgs[0].shape
    if format in yuv420:
        shape = _shape + (1,)
    else:
        shape = _shape

    # generate output tensor shape
    if tensor_fmt == &#39;NCHW&#39;:
        tensor_shape = (len(imgs),) + shape[-1:] + shape[:-1]
    elif tensor_fmt == &#39;NHWC&#39;:
        tensor_shape = (len(imgs),) + shape
    else:
        raise ValueError(
            f&#34;Tensor format only accept &#39;NCHW&#39; or &#39;NHWC&#39;, but got {tensor_fmt}.&#34;)

    if not tensor_ptr:
        tensor = AscendArray(
            tensor_shape, dtype=imgs[0].dtype, format=tensor_fmt)
        _ptr = tensor.ascend_data
    else:
        assert isinstance(tensor_ptr, int), \
            f&#34;Input tensor_ptr expects an int, but got {type(tensor_ptr)}.&#34;
        _ptr = tensor_ptr

    nbytes = 0
    for i, img in enumerate(imgs):
        assert _shape == img.shape, f&#34;imgs[{i}]&#39;s shape {img.shape} is not same to others.&#34;
        assert format == img.format, f&#34;imgs[{i}]&#39;s format {img.shape} is not same to others.&#34;

        if tensor_fmt == &#39;NCHW&#39;:
            # swap channel using transform operator
            &#39;&#39;&#39;
            to do transformer
            &#39;&#39;&#39;
            pass

        nbytes = nbytes + img.nbytes
        memcpy_d2d(_ptr + nbytes, img.ascend_data, img.nbytes)

    return tensor if not tensor_ptr else None</code></pre>
</details>
</dd>
<dt id="ascend.imshow"><code class="name flex">
<span>def <span class="ident">imshow</span></span>(<span>img, win_name='', wait_time=0)</span>
</code></dt>
<dd>
<div class="desc"><p>Show an image.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code> or <code>ndarray</code></dt>
<dd>The image to be displayed.</dd>
<dt><strong><code>win_name</code></strong> :&ensp;<code>str</code></dt>
<dd>The window name.</dd>
<dt><strong><code>wait_time</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of waitKey param.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/image.py#L28-L48" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imshow(img, win_name=&#39;&#39;, wait_time=0):
    &#34;&#34;&#34;Show an image.

    Args:
        img (AscendArray or ndarray): The image to be displayed.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
    &#34;&#34;&#34;
    img = trans_numpy(img)
    cv2.imshow(win_name, img)

    if wait_time == 0:  # prevent from hangning if windows was closed
        while True:
            ret = cv2.waitKey(1)

            closed = cv2.getWindowProperty(win_name, cv2.WND_PROP_VISIBLE) &lt; 1
            # if user closed window or if some key pressed
            if closed or ret != -1:
                break
    else:
        ret = cv2.waitKey(wait_time)</code></pre>
</details>
</dd>
<dt id="ascend.imshow_bboxes"><code class="name flex">
<span>def <span class="ident">imshow_bboxes</span></span>(<span>img, bboxes, colors='green', top_k=-1, thickness=1, show=True, win_name='', wait_time=0, out_file=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Draw bboxes on an image.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code> or <code>ndarray</code></dt>
<dd>The image to be displayed.</dd>
<dt><strong><code>bboxes</code></strong> :&ensp;<code>list</code> or <code>ndarray</code></dt>
<dd>A list of ndarray of shape (k, 4).</dd>
<dt><strong><code>colors</code></strong> :&ensp;<code>list[str</code> or <code>tuple</code> or <code><a title="ascend.Color" href="#ascend.Color">Color</a>]</code></dt>
<dd>A list of colors.</dd>
<dt><strong><code>top_k</code></strong> :&ensp;<code>int</code></dt>
<dd>Plot the first k bboxes only if set positive.</dd>
<dt><strong><code>thickness</code></strong> :&ensp;<code>int</code></dt>
<dd>Thickness of lines.</dd>
<dt><strong><code>show</code></strong> :&ensp;<code>bool</code></dt>
<dd>Whether to show the image.</dd>
<dt><strong><code>win_name</code></strong> :&ensp;<code>str</code></dt>
<dd>The window name.</dd>
<dt><strong><code>wait_time</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of waitKey param.</dd>
<dt><strong><code>out_file</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The filename to write the image.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The image with bboxes drawn on it.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/image.py#L51-L101" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imshow_bboxes(img,
                  bboxes,
                  colors=&#39;green&#39;,
                  top_k=-1,
                  thickness=1,
                  show=True,
                  win_name=&#39;&#39;,
                  wait_time=0,
                  out_file=None):
    &#34;&#34;&#34;Draw bboxes on an image.

    Args:
        img (AscendArray or ndarray): The image to be displayed.
        bboxes (list or ndarray): A list of ndarray of shape (k, 4).
        colors (list[str or tuple or Color]): A list of colors.
        top_k (int): Plot the first k bboxes only if set positive.
        thickness (int): Thickness of lines.
        show (bool): Whether to show the image.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
        out_file (str, optional): The filename to write the image.

    Returns:
        ndarray: The image with bboxes drawn on it.
    &#34;&#34;&#34;
    img = trans_numpy(img)

    if isinstance(bboxes, np.ndarray):
        bboxes = [bboxes]
    if not isinstance(colors, list):
        colors = [colors for _ in range(len(bboxes))]
    colors = [color_val(c) for c in colors]
    assert len(bboxes) == len(colors)

    for i, _bboxes in enumerate(bboxes):
        _bboxes = _bboxes.astype(np.int32)
        if top_k &lt;= 0:
            _top_k = _bboxes.shape[0]
        else:
            _top_k = min(top_k, _bboxes.shape[0])
        for j in range(_top_k):
            left_top = (_bboxes[j, 0], _bboxes[j, 1])
            right_bottom = (_bboxes[j, 2], _bboxes[j, 3])
            cv2.rectangle(
                img, left_top, right_bottom, colors[i], thickness=thickness)

    if show:
        imshow(img, win_name, wait_time)
    if out_file is not None:
        cv2.imwrite(out_file, img)
    return img</code></pre>
</details>
</dd>
<dt id="ascend.imshow_bboxes_colors"><code class="name flex">
<span>def <span class="ident">imshow_bboxes_colors</span></span>(<span>img, bboxes, class_names, colors, score_thr=0, thickness=1, font_scale=0.5, show=True, win_name='', wait_time=0, out_file=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Draw bboxes and class labels (with scores) on an image using various color.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>, ndarray</code></dt>
<dd>The image to be displayed.</dd>
<dt><strong><code>bboxes</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Bounding boxes (with scores, label), shaped (n, 5) or (n, 6).
shape like [x1, y1, x2, y2, scores, classid] or [x1, y1, x2, y2, classid]</dd>
<dt><strong><code>class_names</code></strong> :&ensp;<code>list[str]</code></dt>
<dd>Names of each classes.</dd>
<dt><strong><code>score_thr</code></strong> :&ensp;<code>float</code></dt>
<dd>Minimum score of bboxes to be shown.</dd>
<dt><strong><code>thickness</code></strong> :&ensp;<code>int</code></dt>
<dd>Thickness of lines.</dd>
<dt><strong><code>font_scale</code></strong> :&ensp;<code>float</code></dt>
<dd>Font scales of texts.</dd>
<dt><strong><code>show</code></strong> :&ensp;<code>bool</code></dt>
<dd>Whether to show the image.</dd>
<dt><strong><code>win_name</code></strong> :&ensp;<code>str</code></dt>
<dd>The window name.</dd>
<dt><strong><code>wait_time</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of waitKey param.</dd>
<dt><strong><code>out_file</code></strong> :&ensp;<code>str</code> or <code>None</code></dt>
<dd>The filename to write the image.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The image with bboxes drawn on it.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/image.py#L176-L236" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imshow_bboxes_colors(img,
                   bboxes,
                   class_names,
                   colors,
                   score_thr=0,
                   thickness=1,
                   font_scale=0.5,
                   show=True,
                   win_name=&#39;&#39;,
                   wait_time=0,
                   out_file=None):
    &#34;&#34;&#34;Draw bboxes and class labels (with scores) on an image using various color.

    Args:
        img (AscendArray, ndarray): The image to be displayed.
        bboxes (ndarray): Bounding boxes (with scores, label), shaped (n, 5) or (n, 6).
            shape like [x1, y1, x2, y2, scores, classid] or [x1, y1, x2, y2, classid]

        class_names (list[str]): Names of each classes.
        score_thr (float): Minimum score of bboxes to be shown.
        thickness (int): Thickness of lines.
        font_scale (float): Font scales of texts.
        show (bool): Whether to show the image.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
        out_file (str or None): The filename to write the image.

    Returns:
        ndarray: The image with bboxes drawn on it.
    &#34;&#34;&#34;
    assert bboxes.ndim == 2
    assert bboxes.shape[1] == 5 or bboxes.shape[1] == 6
    assert len(colors) == len(class_names)
    img = trans_numpy(img)

    if score_thr &gt; 0:
        assert bboxes.shape[1] == 6
        scores = bboxes[:, 4]
        inds = scores &gt; score_thr
        bboxes = bboxes[inds, :]

    img = np.ascontiguousarray(img).astype(np.uint8)  # 可能传入的不是uint8

    for bbox, label in zip(bboxes[:,:5], bboxes[:,-1].astype(&#39;int32&#39;)):
        bbox_int = bbox.astype(np.int32)
        left_top = (bbox_int[0], bbox_int[1])
        right_bottom = (bbox_int[2], bbox_int[3])
        cv2.rectangle(
            img, left_top, right_bottom, colors[label], thickness=thickness)
        label_text = class_names[
            label] if class_names is not None else f&#39;cls {label}&#39;
        if len(bbox) &gt; 4:
            label_text += f&#39;|{bbox[-1]:.02f}&#39;
        cv2.putText(img, label_text, (bbox_int[0], bbox_int[1] - 2),
                    cv2.FONT_HERSHEY_COMPLEX, font_scale, colors[label])

    if show:
        imshow(img, win_name, wait_time)
    if out_file is not None:
        cv2.imwrite(out_file, img)
    return img</code></pre>
</details>
</dd>
<dt id="ascend.imshow_det_bboxes"><code class="name flex">
<span>def <span class="ident">imshow_det_bboxes</span></span>(<span>img, bboxes, labels, class_names=None, score_thr=0, bbox_color='green', text_color='green', thickness=1, font_scale=0.5, show=True, win_name='', wait_time=0, out_file=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Draw bboxes and class labels (with scores) on an image.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>, ndarray</code></dt>
<dd>The image to be displayed.</dd>
<dt><strong><code>bboxes</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Bounding boxes (with scores), shaped (n, 4) or
(n, 5).</dd>
<dt><strong><code>labels</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Labels of bboxes.</dd>
<dt><strong><code>class_names</code></strong> :&ensp;<code>list[str]</code></dt>
<dd>Names of each classes.</dd>
<dt><strong><code>score_thr</code></strong> :&ensp;<code>float</code></dt>
<dd>Minimum score of bboxes to be shown.</dd>
<dt><strong><code>bbox_color</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Color of bbox lines. It also accept value of <code><a title="ascend.Color" href="#ascend.Color">Color</a></code>/str/tuple.
Defaults to 'green'.</dd>
<dt><strong><code>text_color</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Color of texts. It also accept value of <code><a title="ascend.Color" href="#ascend.Color">Color</a></code>/str/tuple.
Defaults to 'green'.</dd>
<dt><strong><code>thickness</code></strong> :&ensp;<code>int</code></dt>
<dd>Thickness of lines.</dd>
<dt><strong><code>font_scale</code></strong> :&ensp;<code>float</code></dt>
<dd>Font scales of texts.</dd>
<dt><strong><code>show</code></strong> :&ensp;<code>bool</code></dt>
<dd>Whether to show the image.</dd>
<dt><strong><code>win_name</code></strong> :&ensp;<code>str</code></dt>
<dd>The window name.</dd>
<dt><strong><code>wait_time</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of waitKey param.</dd>
<dt><strong><code>out_file</code></strong> :&ensp;<code>str</code> or <code>None</code></dt>
<dd>The filename to write the image.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The image with bboxes drawn on it.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/image.py#L104-L173" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imshow_det_bboxes(img,
                      bboxes,
                      labels,
                      class_names=None,
                      score_thr=0,
                      bbox_color=&#39;green&#39;,
                      text_color=&#39;green&#39;,
                      thickness=1,
                      font_scale=0.5,
                      show=True,
                      win_name=&#39;&#39;,
                      wait_time=0,
                      out_file=None):
    &#34;&#34;&#34;Draw bboxes and class labels (with scores) on an image.

    Args:
        img (AscendArray, ndarray): The image to be displayed.
        bboxes (ndarray): Bounding boxes (with scores), shaped (n, 4) or
            (n, 5).
        labels (ndarray): Labels of bboxes.
        class_names (list[str]): Names of each classes.
        score_thr (float): Minimum score of bboxes to be shown.
        bbox_color (str, optional): Color of bbox lines. It also accept value of `Color`/str/tuple. 
            Defaults to &#39;green&#39;.
        text_color (str, optional): Color of texts. It also accept value of `Color`/str/tuple. 
            Defaults to &#39;green&#39;.
        thickness (int): Thickness of lines.
        font_scale (float): Font scales of texts.
        show (bool): Whether to show the image.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
        out_file (str or None): The filename to write the image.

    Returns:
        ndarray: The image with bboxes drawn on it.
    &#34;&#34;&#34;
    assert bboxes.ndim == 2
    assert labels.ndim == 1
    assert bboxes.shape[0] == labels.shape[0]
    assert bboxes.shape[1] == 4 or bboxes.shape[1] == 5
    img = trans_numpy(img)

    if score_thr &gt; 0:
        assert bboxes.shape[1] == 5
        scores = bboxes[:, -1]
        inds = scores &gt; score_thr
        bboxes = bboxes[inds, :]
        labels = labels[inds]

    bbox_color = color_val(bbox_color)
    text_color = color_val(text_color)
    img = np.ascontiguousarray(img).astype(np.uint8)  # 可能传入的不是uint8
    for bbox, label in zip(bboxes, labels):
        bbox_int = bbox.astype(np.int32)
        left_top = (bbox_int[0], bbox_int[1])
        right_bottom = (bbox_int[2], bbox_int[3])
        cv2.rectangle(
            img, left_top, right_bottom, bbox_color, thickness=thickness)
        label_text = class_names[
            label] if class_names is not None else f&#39;cls {label}&#39;
        if len(bbox) &gt; 4:
            label_text += f&#39;|{bbox[-1]:.02f}&#39;
        cv2.putText(img, label_text, (bbox_int[0], bbox_int[1] - 2),
                    cv2.FONT_HERSHEY_COMPLEX, font_scale, text_color)

    if show:
        imshow(img, win_name, wait_time)
    if out_file is not None:
        cv2.imwrite(out_file, img)
    return img</code></pre>
</details>
</dd>
<dt id="ascend.is_filepath"><code class="name flex">
<span>def <span class="ident">is_filepath</span></span>(<span>x)</span>
</code></dt>
<dd>
<div class="desc"><p>judge x is a filepath</p>
<h2 id="args">Args</h2>
<p>x : input x</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[bool]</code></dt>
<dd>&nbsp;</dd>
</dl>
<ul>
<li>True: for x is filepath, </li>
<li>False: for x is not filepath</li>
</ul></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/common/path.py#L34-L45" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def is_filepath(x):
    &#34;&#34;&#34;judge x is a filepath

    Args:
        x : input x

    Returns:
        [bool]: 
        - True: for x is filepath, 
        - False: for x is not filepath
    &#34;&#34;&#34;    
    return is_str(x) or isinstance(x, Path)</code></pre>
</details>
</dd>
<dt id="ascend.mkdir_or_exist"><code class="name flex">
<span>def <span class="ident">mkdir_or_exist</span></span>(<span>dir_name, mode=511)</span>
</code></dt>
<dd>
<div class="desc"><p>Make a directory</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>dir_name</code></strong> :&ensp;<code>str</code></dt>
<dd>The directory name</dd>
<dt><strong><code>mode</code></strong> :&ensp;<code>number</code>, optional</dt>
<dd>The directory's permission. Defaults to 0o777.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/common/path.py#L67-L77" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def mkdir_or_exist(dir_name, mode=0o777):
    &#34;&#34;&#34;Make a directory

    Args:
        dir_name (str): The directory name
        mode (number, optional): The directory&#39;s permission. Defaults to 0o777.
    &#34;&#34;&#34;    
    if dir_name == &#39;&#39;:
        return
    dir_name = osp.expanduser(dir_name)
    os.makedirs(dir_name, mode=mode, exist_ok=True)</code></pre>
</details>
</dd>
<dt id="ascend.nms"><code class="name flex">
<span>def <span class="ident">nms</span></span>(<span>boxes, scores, nms_thresh=0.3)</span>
</code></dt>
<dd>
<div class="desc"><p>Suppress overlapping detected bbox.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>boxes</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Input bboxes with shape (n, 4)</dd>
<dt><strong><code>scores</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Input scores with shape (k, 4) of bboxes</dd>
<dt><strong><code>nms_thresh</code></strong> :&ensp;<code>float</code>, optional</dt>
<dd>The threshold of iou (intersection over union).
Defaults to 0.3.</dd>
</dl>
<h2 id="returns">Returns</h2>
<p>keep (ndarray): The result of nms</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/nms.py#L17-L65" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def nms(boxes, scores, nms_thresh=0.3):
    &#34;&#34;&#34;Suppress overlapping detected bbox.

    Args:
        boxes (ndarray): Input bboxes with shape (n, 4)
        scores (ndarray): Input scores with shape (k, 4) of bboxes
        nms_thresh (float, optional): The threshold of iou (intersection over union). 
            Defaults to 0.3.

    Returns:
        keep (ndarray): The result of nms
    &#34;&#34;&#34;
    x1 = boxes[:, 0]
    y1 = boxes[:, 1]
    x2 = boxes[:, 2]
    y2 = boxes[:, 3]
    areas = (x2 - x1 + 1) * (y2 - y1 + 1)
    order = np.argsort(scores)[::-1]
    num_det = boxes.shape[0]
    suppressed = np.zeros((num_det,), dtype=np.bool)

    keep = []
    for _i in range(num_det):
        i = order[_i]
        if suppressed[i]:
            continue
        keep.append(i)

        ix1, iy1, ix2, iy2 = x1[i], y1[i], x2[i], y2[i]
        iarea = areas[i]

        for _j in range(_i + 1, num_det):
            j = order[_j]
            if suppressed[j]:
                continue

            xx1 = max(ix1, x1[j])
            yy1 = max(iy1, y1[j])
            xx2 = min(ix2, x2[j])
            yy2 = min(iy2, y2[j])
            w = max(0, xx2 - xx1 + 1)
            h = max(0, yy2 - yy1 + 1)

            inter = w * h
            ovr = inter / (iarea + areas[j] - inter)
            if ovr &gt;= nms_thresh:
                suppressed[j] = True

    return keep</code></pre>
</details>
</dd>
<dt id="ascend.rgb2ycbcr"><code class="name flex">
<span>def <span class="ident">rgb2ycbcr</span></span>(<span>img, y_only=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert a RGB image to YCbCr image.</p>
<p>This function produces the same results as Matlab's <code><a title="ascend.rgb2ycbcr" href="#ascend.rgb2ycbcr">rgb2ycbcr()</a></code> function.
It implements the ITU-R BT.601 conversion for standard-definition
television. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.">https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.</a></p>
<p>It differs from a similar function in cv2.cvtColor: <code>RGB &lt;-&gt; YCrCb</code>.
In OpenCV, it implements a JPEG conversion. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.">https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.</a></p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The input image. It accepts:</dd>
</dl>
<ul>
<li>np.uint8 type with range [0, 255];</li>
<li>np.float16 type with range [0, 1].</li>
</ul>
<dl>
<dt><strong><code>y_only</code></strong> :&ensp;<code>bool</code></dt>
<dd>Whether to only return Y channel. Default: False.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The converted YCbCr image. The output image has the same type
and range as input image.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/colorspace.py#L73-L120" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def rgb2ycbcr(img, y_only=False):
    &#34;&#34;&#34;Convert a RGB image to YCbCr image.

    This function produces the same results as Matlab&#39;s `rgb2ycbcr` function.
    It implements the ITU-R BT.601 conversion for standard-definition
    television. See more details in
    https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.

    It differs from a similar function in cv2.cvtColor: `RGB &lt;-&gt; YCrCb`.
    In OpenCV, it implements a JPEG conversion. See more details in
    https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.

    Args:
        img (AscendArray): The input image. It accepts:

        - np.uint8 type with range [0, 255];
        - np.float16 type with range [0, 1].

        y_only (bool): Whether to only return Y channel. Default: False.

    Returns:
        AscendArray: The converted YCbCr image. The output image has the same type
            and range as input image.
    &#34;&#34;&#34;
    img_type = img.dtype
    img = _convert_input_type_range(img)
    if y_only:
        # out_img = np.dot(img, [65.481, 128.553, 24.966]) + 16.0
        trans = np.array([65.481, 128.553, 24.966], dtype=np.float16)
        bias = np.array([16.0], dtype=np.float16)
    else:
        trans = np.array([[ 65.481, -37.797,   112.0], 
                          [128.553, -74.203, -93.786],
                          [ 24.966,   112.0, -18.214]], dtype=np.float16)
        bias = np.array([16, 128, 128], dtype=np.float16)

    # clone to device
    trans = AscendArray.clone(trans)
    bias = AscendArray.clone(bias)

    if y_only:
        # do transmit
        out_inst = Vmul(img, trans, bias)
    else:
        # do transmit
        out_inst = Matmul(img, trans, bias)
    out_img = _convert_output_type_range(out_inst.out, img_type)
    return out_img</code></pre>
</details>
</dd>
<dt id="ascend.run_mode"><code class="name flex">
<span>def <span class="ident">run_mode</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>get run mode of Ascend310. </p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>running mode </code></dt>
<dd>&nbsp;</dd>
</dl>
<ul>
<li><code>0</code> for evaluate board or Atlas200 on ctrl-cpu; </li>
<li><code>1</code> for standard Inference card(Atlas300-3000/Atlas300-3010/Atlas800-3000/Atlas500/
Atlas500pro) on host-cpu
Typical usage example:</li>
</ul>
<pre><code class="language-python">mode = ascend.run_mode()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L40-L61" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run_mode():
    &#34;&#34;&#34; get run mode of Ascend310. 

    Args:
        None

    Returns:
        running mode : 
        - `0` for evaluate board or Atlas200 on ctrl-cpu; 
        - `1` for standard Inference card(Atlas300-3000/Atlas300-3010/Atlas800-3000/Atlas500/
            Atlas500pro) on host-cpu
        
    Typical usage example:
    ```python
    mode = ascend.run_mode()
    ``` 
    &#34;&#34;&#34;
    run_mode, ret = acl.rt.get_run_mode()
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;pyACL is not installed or isinvalid.&#34;)

    return run_mode</code></pre>
</details>
</dd>
<dt id="ascend.show_bbox"><code class="name flex">
<span>def <span class="ident">show_bbox</span></span>(<span>image, bboxs_list, color=None, thickness=1, font_scale=0.3, wait_time_ms=0, names=None, is_show=True, is_without_mask=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Visualize bbox in object detection by drawing rectangle. Notice, when you using this function,
you'd better install opencv first.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>image</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Input image to be drawed with lines and labels.</dd>
<dt><strong><code>bboxs_list</code></strong> :&ensp;<code>list</code></dt>
<dd>A list with [pts_xyxy, prob, id], the preditction</dd>
<dt><strong><code>color</code></strong> :&ensp;<code>tuple</code>, optional</dt>
<dd>The bbox's color. Defaults to None.</dd>
<dt><strong><code>thickness</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>The thickness of line. Defaults to 1.</dd>
<dt><strong><code>font_scale</code></strong> :&ensp;<code>float</code>, optional</dt>
<dd>The font scale of bbox. Defaults to 0.3.</dd>
<dt><strong><code>wait_time_ms</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Image's views time interval. Defaults to 0.</dd>
<dt><strong><code>names</code></strong> :&ensp;<code>[type]</code>, optional</dt>
<dd>Figure's window name. Defaults to None.</dd>
<dt><strong><code>is_show</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Show the image or not. Defaults to True.</dd>
<dt><strong><code>is_without_mask</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Defaults to False.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>A image with bbox and text</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">ascend.show_bbox(image, bboxes, wait_time_ms=10)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/misc.py#L114-L180" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def show_bbox(image, bboxs_list, color=None, thickness=1, font_scale=0.3, wait_time_ms=0, names=None,
              is_show=True, is_without_mask=False):
    &#34;&#34;&#34;Visualize bbox in object detection by drawing rectangle. Notice, when you using this function, 
    you&#39;d better install opencv first.

    Args:
        image (AscendArray): Input image to be drawed with lines and labels.
        bboxs_list (list): A list with [pts_xyxy, prob, id], the preditction
        color (tuple, optional): The bbox&#39;s color. Defaults to None.
        thickness (int, optional): The thickness of line. Defaults to 1.
        font_scale (float, optional): The font scale of bbox. Defaults to 0.3.
        wait_time_ms (int, optional): Image&#39;s views time interval. Defaults to 0.
        names ([type], optional): Figure&#39;s window name. Defaults to None.
        is_show (bool, optional): Show the image or not. Defaults to True.
        is_without_mask (bool, optional): Defaults to False.

    Returns:
        ndarray: A image with bbox and text

    Typical usage example:
    ```python
    ascend.show_bbox(image, bboxes, wait_time_ms=10)
    ```
    &#34;&#34;&#34;
    try:
        import cv2
    except ImportError:
        Log(ERROR, f&#34;import cv2 error while using show_bbox, and you should install opencv first.&#34;)
        return

    if not isinstance(image, AscendArray):
        raise TypeError(f&#34;Input image expects an AscendArray, but got {type(image)}.&#34;)

    font = cv2.FONT_HERSHEY_SIMPLEX
    image_copy = image.to_np
    if image.format == PIXEL_FORMAT_YUV_SEMIPLANAR_420:
        image_copy = cv2.cvtColor(image_copy, cv2.COLOR_YUV2RGB_NV21)
    elif image.format == PIXEL_FORMAT_YVU_SEMIPLANAR_420:
        image_copy = cv2.cvtColor(image_copy, cv2.COLOR_YUV2RGB_NV12)

    for bbox in bboxs_list:
        if len(bbox) == 5:
            txt = &#39;{:.3f}&#39;.format(bbox[4])
        elif len(bbox) == 6:
            txt = &#39;p={:.3f},id={:.3f}&#39;.format(bbox[4], bbox[5])
        bbox_f = np.array(bbox[:4], np.int32)
        if color is None:
            colors = random_color(rgb=True).astype(np.float64)
        else:
            colors = color

        if not is_without_mask:
            image_copy = cv2.rectangle(image_copy, (bbox_f[0], bbox_f[1]), (bbox_f[2], bbox_f[3]), colors,
                                       thickness)
        else:
            mask = np.zeros_like(image_copy, np.uint8)
            mask1 = cv2.rectangle(mask, (bbox_f[0], bbox_f[1]), (bbox_f[2], bbox_f[3]), colors, -1)
            mask = np.zeros_like(image_copy, np.uint8)
            mask2 = cv2.rectangle(mask, (bbox_f[0], bbox_f[1]), (bbox_f[2], bbox_f[3]), colors, thickness)
            mask2 = cv2.addWeighted(mask1, 0.5, mask2, 8, 0.0)
            image_copy = cv2.addWeighted(image_copy, 1.0, mask2, 0.6, 0.0)
        if len(bbox) == 5 or len(bbox) == 6:
            cv2.putText(image_copy, txt, (bbox_f[0], bbox_f[1] - 2),
                        font, font_scale, (255, 255, 255), thickness=thickness, lineType=cv2.LINE_AA)
    if is_show:
        show_img(image_copy, names, wait_time_ms)
    return image_copy</code></pre>
</details>
</dd>
<dt id="ascend.show_growth"><code class="name flex">
<span>def <span class="ident">show_growth</span></span>(<span>show_cnt=0)</span>
</code></dt>
<dd>
<div class="desc"><p>Show python object references growth, the default show_cnt is 0.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>show_cnt</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Debug memory release for show_cnt = 2. Defaults to 0.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">ascend.show_graph()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/common/graph.py#L18-L39" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def show_growth(show_cnt=0):
    &#34;&#34;&#34;Show python object references growth, the default show_cnt is 0.

    Args:
        show_cnt (int, optional): Debug memory release for show_cnt = 2. Defaults to 0.

    Typical usage example:
    ```python
    ascend.show_graph()
    ```
    &#34;&#34;&#34;    
    print(&#34;------------------------&#34;)
    objgraph.show_growth()
    type_list = [&#39;list&#39;, &#39;tuple&#39;, &#39;dict&#39;, &#39;method&#39;, &#39;weakref&#39;]
    print_str = &#34;objgraph.by_type:\n&#34;

    for by_type in type_list:
        type_len = len(objgraph.by_type(by_type))
        start = type_len - 1
        end = start - show_cnt
        print_str += f&#34;{by_type} = {objgraph.by_type(by_type)[start:end:-1]}\n&#34;
    print(print_str)</code></pre>
</details>
</dd>
<dt id="ascend.show_img"><code class="name flex">
<span>def <span class="ident">show_img</span></span>(<span>imgs, window_names=None, wait_time_ms=0)</span>
</code></dt>
<dd>
<div class="desc"><p>Displays an image or a list of images in specified windows or self-initiated windows.
You can also control display wait time by parameter 'wait_time_ms'.
Notice, specified format must be greater than or equal to imgs number. When you using this
function, you'd better install opencv first.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>imgs</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>, ndarray</code> or <code>list</code></dt>
<dd>Input images.</dd>
<dt><strong><code>window_names</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>If None, function will create different windows as '1', '2'.</dd>
<dt><strong><code>wait_time_ms</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Display wait time.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">ascend.show_img(image, wait_time_ms=15)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/misc.py#L21-L64" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def show_img(imgs, window_names=None, wait_time_ms=0):
    &#34;&#34;&#34;Displays an image or a list of images in specified windows or self-initiated windows.
        You can also control display wait time by parameter &#39;wait_time_ms&#39;.
        Notice, specified format must be greater than or equal to imgs number. When you using this 
        function, you&#39;d better install opencv first.

    Args:
        imgs (AscendArray, ndarray or list): Input images.
        window_names (str, optional): If None, function will create different windows as &#39;1&#39;, &#39;2&#39;.
        wait_time_ms (int, optional): Display wait time.

    Typical usage example:
    ```python
    ascend.show_img(image, wait_time_ms=15)
    ```
    &#34;&#34;&#34;
    try:
        import cv2
    except ImportError:
        Log(ERROR, f&#34;import cv2 error while using show_img, and you should install opencv first.&#34;)
        return

    if not isinstance(imgs, list):
        imgs = [imgs]

    if window_names is None:
        window_names = list(range(len(imgs)))
    else:
        if not isinstance(window_names, list):
            window_names = [window_names]
        assert len(imgs) == len(window_names), &#39;window names does not match images!&#39;

    show_imgs = []
    for i, img in enumerate(imgs):
        show_imgs.append(img.to_np if isinstance(img, AscendArray) else img)
 
    for img, win_name in zip(show_imgs, window_names):
        if img is None:
            continue
        win_name = str(win_name)
        cv2.namedWindow(win_name, 0)
        cv2.imshow(win_name, img)

    cv2.waitKey(wait_time_ms)</code></pre>
</details>
</dd>
<dt id="ascend.show_tensor"><code class="name flex">
<span>def <span class="ident">show_tensor</span></span>(<span>tensor, resize_hw=None, is_show=True, wait_time_ms=0)</span>
</code></dt>
<dd>
<div class="desc"><p>Show tensor as heatmap.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>tensor</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Input tensor</dd>
<dt><strong><code>resize_hw</code></strong> :&ensp;<code>tuple</code>, optional</dt>
<dd>Wether to resize the input tensor to fit the window. Defaults to None.</dd>
<dt><strong><code>is_show</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Show the tensor or save it. Defaults to True.</dd>
<dt><strong><code>wait_time_ms</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Display time. Defaults to 0.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code></dt>
<dd>Converted tensor heatmap.</dd>
</dl>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>When you using this function, you'd better install opencv first.</p>
</div>
<p>Typical usage example:</p>
<pre><code class="language-python">ascend.show_tensor(tensor, resize_hw=(640, 480), wait_time_ms=10)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/misc.py#L183-L252" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def show_tensor(tensor, resize_hw=None, is_show=True, wait_time_ms=0):
    &#34;&#34;&#34;Show tensor as heatmap.

    Args:
        tensor (AscendArray): Input tensor
        resize_hw (tuple, optional): Wether to resize the input tensor to fit the window. Defaults to None.
        is_show (bool, optional): Show the tensor or save it. Defaults to True.
        wait_time_ms (int, optional): Display time. Defaults to 0.

    Returns:
        list[AscendArray]: Converted tensor heatmap.

    .. warning::
        When you using this function, you&#39;d better install opencv first.

    Typical usage example:
    ```python
    ascend.show_tensor(tensor, resize_hw=(640, 480), wait_time_ms=10)
    ```
    &#34;&#34;&#34;
    try:
        import cv2
    except ImportError:
        Log(ERROR, f&#34;import cv2 error while using show_tensor, and you should install opencv first.&#34;)
        return

    def normalize_numpy(array):
        max_value = np.max(array)
        min_value = np.min(array)
        array = (array - min_value) / (max_value - min_value)
        return array

    if not isinstance(tensor, AscendArray):
        raise TypeError(f&#34;Input tensor expects an AscendArray, but got {type(tensor)}.&#34;)
        
    if tensor.ndim != 4:
        raise ValueError(&#39;Dim of input tensor should be 4, please check your tensor dimension!&#39;)

    if tensor.format == &#39;NCHW&#39;:
        tensor = tensor
    else:
        &#39;&#39;&#39;
        to transpose NCHW, using ascend310 first. if it fails, use numpy.
        &#39;&#39;&#39;
        try:
            tensor = Permute(tensor, axes=(0, 2, 3, 1))
        except:
            tensor = tensor.to_np.transpose((0, 2, 3, 1))

    # resize the tensor with interpolize
    if resize_hw is not None:
        pass

    tensor = tensor.permute(1, 2, 0)

    channel = tensor.shape[2]
    tensor = tensor.to_np
  
    # do normalize
    sum_tensor = np.sum(tensor, axis=2)
    sum_tensor = normalize_numpy(sum_tensor) * 255
    sum_tensor = sum_tensor.astype(np.uint8)

    # show tensor as colormap
    sum_tensor = cv2.applyColorMap(np.uint8(sum_tensor), cv2.COLORMAP_JET)
    # mean_tensor = cv2.applyColorMap(np.uint8(mean_tensor), cv2.COLORMAP_JET)

    if is_show:
        show_img([sum_tensor], [&#39;sum&#39;], wait_time_ms=wait_time_ms)
    return [sum_tensor]</code></pre>
</details>
</dd>
<dt id="ascend.tensor2imgs"><code class="name flex">
<span>def <span class="ident">tensor2imgs</span></span>(<span>tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert tensor to a 3-channel images</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>tensor</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Tensor that contains multiple images, shape (N, C, H, W) or shape (N, H, W, C)</dd>
<dt><strong><code>mean</code></strong> :&ensp;<code>tuple[float]</code>, optional</dt>
<dd>The mean value of images. Defaults to (0, 0, 0).</dd>
<dt><strong><code>std</code></strong> :&ensp;<code>tuple[float]</code>, optional</dt>
<dd>The standard deviation of images. Defaults to (1, 1, 1).</dd>
<dt><strong><code>to_rgb</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Whether the tensor was converted to RGB format in the first place.
If so, convert it back to BGR. Defaults to True.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list[np.ndarray]</code></dt>
<dd>A list that contains multiple images.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">imgs = ascend.tensor2imgs(tensors)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/tensor.py#L109-L161" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def tensor2imgs(tensor, mean=(0, 0, 0), std=(1, 1, 1), to_rgb=True):
    &#34;&#34;&#34;Convert tensor to a 3-channel images

    Args:
        tensor (AscendArray): Tensor that contains multiple images, shape (N, C, H, W) or shape (N, H, W, C)
        mean (tuple[float], optional): The mean value of images. Defaults to (0, 0, 0).
        std (tuple[float], optional): The standard deviation of images. Defaults to (1, 1, 1).
        to_rgb (bool, optional): Whether the tensor was converted to RGB format in the first place.
            If so, convert it back to BGR. Defaults to True.

    Returns:
        list[np.ndarray]: A list that contains multiple images.

    Typical usage example:
    ```python
    imgs = ascend.tensor2imgs(tensors)
    ```
    &#34;&#34;&#34;
    if not isinstance(tensor, AscendArray):
        raise TypeError(
            f&#34;Input tensor expects an AscendArray, but got {type(tensor)}.&#34;)

    if tensor.ndim != 4:
        raise ValueError(
            f&#34;Input tensor expects a 4-dim, but got {tensor.ndim}.&#34;)

    if tensor.format not in [&#34;NCHW&#34;, &#34;NHWC&#34;]:
        raise ValueError(
            f&#34;Input tensor&#39;s format only support &#39;NCHW&#39; or &#39;NHWC&#39;, but given {tensor.format}.&#34;)

    assert len(mean) == 3, \
        f&#34;Input mean of images expects a 3-elements tuple, but got {len(mean)}.&#34;
    assert len(std) == 3, \
        f&#34;Input std of images expects a 3-elements tuple, but got {len(std)}.&#34;

    batch_size = tensor.shape[0]
    mean = np.array(mean, dtype=np.float32)
    std = np.array(std, dtype=np.float32)

    if tensor.format == &#34;NCHW&#34;:
        try:
            tensor = Permute(tensor, axes=(0, 2, 3, 1))
        except:
            tensor = tensor.to_np.transpose(0, 2, 3, 1)
    else:
        tensor = tensor.to_np

    imgs = []
    for img_id in range(batch_size):
        img = tensor[img_id, ...]
        img = _imdenormalize(img, mean, std, to_bgr=to_rgb).astype(np.uint8)
        imgs.append(np.ascontiguousarray(img))
    return imgs</code></pre>
</details>
</dd>
<dt id="ascend.voc_classes"><code class="name flex">
<span>def <span class="ident">voc_classes</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>VOC classes</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>VOC classes</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L11-L21" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def voc_classes():
    &#34;&#34;&#34;VOC classes

    Returns:
        list: VOC classes
    &#34;&#34;&#34;    
    return [
        &#39;aeroplane&#39;, &#39;bicycle&#39;, &#39;bird&#39;, &#39;boat&#39;, &#39;bottle&#39;, &#39;bus&#39;, &#39;car&#39;, &#39;cat&#39;,
        &#39;chair&#39;, &#39;cow&#39;, &#39;diningtable&#39;, &#39;dog&#39;, &#39;horse&#39;, &#39;motorbike&#39;, &#39;person&#39;,
        &#39;pottedplant&#39;, &#39;sheep&#39;, &#39;sofa&#39;, &#39;train&#39;, &#39;tvmonitor&#39;
    ]</code></pre>
</details>
</dd>
<dt id="ascend.wider_face_classes"><code class="name flex">
<span>def <span class="ident">wider_face_classes</span></span>(<span>)</span>
</code></dt>
<dd>
<div class="desc"><p>Wider face classes.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>face class</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/class_names.py#L2-L8" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def wider_face_classes():
    &#34;&#34;&#34;Wider face classes.

    Returns:
        list: face class
    &#34;&#34;&#34;    
    return [&#39;face&#39;]</code></pre>
</details>
</dd>
<dt id="ascend.ycbcr2bgr"><code class="name flex">
<span>def <span class="ident">ycbcr2bgr</span></span>(<span>img)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert a YCbCr image to BGR image.</p>
<p>It implements the ITU-R BT.601 conversion for standard-definition
television. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.">https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.</a></p>
<p>It differs from a similar function in cv2.cvtColor: <code>YCrCb &lt;-&gt; BGR</code>.
In OpenCV, it implements a JPEG conversion. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.">https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.</a></p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>The input image. It accepts:</dd>
</dl>
<ul>
<li>np.uint8 type with range [0, 255];</li>
<li>np.float16 type with range [0, 1].</li>
</ul>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The converted BGR image. The output image has the same type
and range as input image.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/colorspace.py#L216-L257" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def ycbcr2bgr(img):
    &#34;&#34;&#34;Convert a YCbCr image to BGR image.

    It implements the ITU-R BT.601 conversion for standard-definition
    television. See more details in
    https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.

    It differs from a similar function in cv2.cvtColor: `YCrCb &lt;-&gt; BGR`.
    In OpenCV, it implements a JPEG conversion. See more details in
    https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.

    Args:
        img (ndarray): The input image. It accepts:

        - np.uint8 type with range [0, 255];
        - np.float16 type with range [0, 1].

    Returns:
        ndarray: The converted BGR image. The output image has the same type
            and range as input image.
    &#34;&#34;&#34;
    img_type = img.dtype
    &#39;&#39;&#39;
    to do denormalize
    &#39;&#39;&#39;
    img = _convert_input_type_range(img) * 255

    trans = np.array([[0.00456621,  0.00456621, 0.00456621], 
                      [0.00791071, -0.00153632,          0],
                      [         0, -0.00318811, 0.00625893]], dtype=np.float16)

    bias = np.array([-276.836, 135.576, -222.921], dtype=np.float16) 

    # clone to device
    trans = AscendArray.clone(trans)
    bias = AscendArray.clone(bias)

    # do transmit
    out_inst = Matmul(img, trans, bias, alpha=255.0)

    out_img = _convert_output_type_range(out_inst.out, img_type)
    return out_img</code></pre>
</details>
</dd>
<dt id="ascend.ycbcr2rgb"><code class="name flex">
<span>def <span class="ident">ycbcr2rgb</span></span>(<span>img)</span>
</code></dt>
<dd>
<div class="desc"><p>Convert a YCbCr image to RGB image.</p>
<p>This function produces the same results as Matlab's ycbcr2rgb function.
It implements the ITU-R BT.601 conversion for standard-definition
television. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.">https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.</a></p>
<p>It differs from a similar function in cv2.cvtColor: <code>YCrCb &lt;-&gt; RGB</code>.
In OpenCV, it implements a JPEG conversion. See more details in
<a href="https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.">https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.</a></p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>The input image. It accepts:</dd>
</dl>
<ul>
<li>np.uint8 type with range [0, 255];</li>
<li>np.float16 type with range [0, 1].</li>
</ul>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>ndarray</code></dt>
<dd>The converted RGB image. The output image has the same type
and range as input image.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/colorspace.py#L172-L213" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def ycbcr2rgb(img):
    &#34;&#34;&#34;Convert a YCbCr image to RGB image.

    This function produces the same results as Matlab&#39;s ycbcr2rgb function.
    It implements the ITU-R BT.601 conversion for standard-definition
    television. See more details in
    https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion.

    It differs from a similar function in cv2.cvtColor: `YCrCb &lt;-&gt; RGB`.
    In OpenCV, it implements a JPEG conversion. See more details in
    https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion.

    Args:
        img (ndarray): The input image. It accepts:
        
        - np.uint8 type with range [0, 255];
        - np.float16 type with range [0, 1].

    Returns:
        ndarray: The converted RGB image. The output image has the same type
            and range as input image.
    &#34;&#34;&#34;
    img_type = img.dtype
    &#39;&#39;&#39;
    to do denormalize
    &#39;&#39;&#39;
    img = _convert_input_type_range(img) * 255

    trans = np.array([[0.00456621,  0.00456621, 0.00456621], 
                      [         0, -0.00153632, 0.00791071],
                      [0.00625893, -0.00318811,          0]], dtype=np.float16)

    bias = np.array([-222.921, 135.576, -276.836], dtype=np.float16) 

    # clone to device
    trans = AscendArray.clone(trans)
    bias = AscendArray.clone(bias)

    # do transmit
    out_inst = Matmul(img, trans, bias, alpha=255.0)
    out_img = _convert_output_type_range(out_inst.out, img_type)
    return out_img</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="ascend.ArgMax"><code class="flex name class">
<span>class <span class="ident">ArgMax</span></span>
<span>(</span><span>input, axis=0, context=None, stream=None)</span>
</code></dt>
<dd>
<div class="desc"><p>define a ArgMax operator.</p>
<h2 id="args">Args</h2>
<dl>
<dt>input
: input tensor (AscendArray)</dt>
<dt>size
: output data size</dt>
<dt><strong><code>context</code></strong></dt>
<dd>input context, optinal</dd>
</dl>
<p>stream : input stream, optinal
function:
run
: do argmax
out
: return output result</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L106-L203" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class ArgMax():
    &#34;&#34;&#34; define a ArgMax operator.

    Args:
        input  : input tensor (AscendArray)
        size   : output data size
        context: input context, optinal
        stream : input stream, optinal

    function:
        run    : do argmax
        out    : return output result
    &#34;&#34;&#34;
    def __init__(self, input, axis=0, context=None, stream=None):
        if not isinstance(input, AscendArray):
            raise TypeError(f&#34;Input tensor expects a AscendArray, but got {type(input)}.&#34;)

        if context and not isinstance(context, int):
            raise TypeError(f&#34;Input context expects an int, but got {type(context)}.&#34;)

        if stream and not isinstance(stream, int):
            raise TypeError(f&#34;Input stream expects an int, but got {type(stream)}.&#34;)

        if axis &gt;= input.ndim:
            raise ValueError(f&#34;Input axis should in range [0, {input.ndim}).&#34;)

        # assign self value
        self.input = input
        self.context = context
        self.stream = stream if stream else create_stream(context)
        self.created = stream is None

        # set op model dir
        OpSet()
        self.__pre_set()

        # create output array to save result
        shape = input.shape[:axis] + input.shape[axis + 1:]
        self._dim = AscendArray.clone(np.array(axis, dtype=np.int32))
        self._out = AscendArray(shape, dtype=np.int32)

        self.tensor_in = TensorDesc(input)
        self.tensor_dim = TensorDesc(self._dim)
        self.tensor_out = TensorDesc(self._out)

        # do cast operator
        self.run()

    def __pre_set(self):
        &#34;&#34;&#34; set op name and attribute.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        self.op_name = &#34;ArgMaxV2&#34;
        self.op_attr = acl.op.create_attr()

    def run(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        # do op excute
        ret = acl.op.execute(self.op_name,
                             [self.tensor_in.desc, self.tensor_dim.desc],
                             [self.tensor_in.buff, self.tensor_dim.buff],
                             [self.tensor_out.desc],
                             [self.tensor_out.buff],
                             self.op_attr,
                             self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to excute op {self.op_name}, return {ret}.&#34;)

        # do synchronize stream 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in excute op, return {ret}.&#34;)
    
    @property
    def data(self):
        return self._out

    def __del__(self):
        if hasattr(self, &#39;_out&#39;):
            del self._out
        if hasattr(self, &#39;tensor_out&#39;):
            del self.tensor_out
        if hasattr(self, &#39;tensor_in&#39;):
            del self.tensor_in

        if self.created:
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, f&#34;destroy stream failed, return {ret}.&#34;</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.ArgMax.data"><code class="name">var <span class="ident">data</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L189-L191" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def data(self):
    return self._out</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.ArgMax.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L165-L187" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    # do op excute
    ret = acl.op.execute(self.op_name,
                         [self.tensor_in.desc, self.tensor_dim.desc],
                         [self.tensor_in.buff, self.tensor_dim.buff],
                         [self.tensor_out.desc],
                         [self.tensor_out.buff],
                         self.op_attr,
                         self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to excute op {self.op_name}, return {ret}.&#34;)

    # do synchronize stream 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in excute op, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.AscendArray"><code class="flex name class">
<span>class <span class="ident">AscendArray</span></span>
<span>(</span><span>shape, dtype, size=0, buffer=None, format=None, context=None, flag='DEVICE')</span>
</code></dt>
<dd>
<div class="desc"><p>Define a AscendArray data class like numpy ndarray.</p>
<pre><code>class private attributes:
_nbytes (int)    : the bytes of AscendArray's data
_shape (tuple)   : the shape of this array
_dtype (int)     : the acl data type of AscendArray
_flag (int)      : the flag of defined memory malloc on device/host/dvpp
_mem (instance)  : save the instance of class Memory()
_data (a pointer): the mem ptr of AscendArray's data
</code></pre>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>ascend_data</code></strong> :&ensp;<code>int</code></dt>
<dd>Get(read) the pointer of data malloced by itself(_data's value),
or band it to a new memory.</dd>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple</code></dt>
<dd>Tuple of array dimensions. (should work with write ascend_data).</dd>
<dt><strong><code>ndim</code></strong> :&ensp;<code>int</code></dt>
<dd>Number of array dimensions.</dd>
<dt><strong><code>dtype</code></strong> :&ensp;<code>np.dtype</code></dt>
<dd>get or write the data type.</dd>
<dt><strong><code>size</code></strong> :&ensp;<code>int</code></dt>
<dd>Number of elements in the array.</dd>
<dt><strong><code>nbytes</code></strong> :&ensp;<code>int</code></dt>
<dd>Total bytes consumed by the elements of the array.</dd>
<dt><strong><code>itemsize</code></strong> :&ensp;<code>int</code></dt>
<dd>Length of one AscendArray element in bytes, which equal to size * dtype(size).</dd>
<dt><strong><code>flag</code></strong> :&ensp;<code>str</code></dt>
<dd>Information about the memory layout of the array.</dd>
</dl>
<div class="admonition hint">
<p class="admonition-title">Hint</p>
<ul>
<li>reshape
: Gives a new shape to an array without changing its data.</li>
<li>resize
: Return a new array with the specified shape.</li>
<li>to_np
: Use this function to copy device data to host and formal like numpy array.</li>
<li>to_ascend : trans a ndarray data to AscendArray(i.e. feed this instance with a numpy array data).</li>
<li>clone
: new a AscendArray object clone from np.ndarray</li>
<li>to
: copy this instance's data to another same shape AscendArray.</li>
<li>astype
: Copy of the array, cast to a specified type.</li>
<li>transpose : Reverse or permute the axes of an array; returns the modified array.</li>
</ul>
</div></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L21-L567" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class AscendArray():
    &#34;&#34;&#34;Define a AscendArray data class like numpy ndarray.

        class private attributes:
        _nbytes (int)    : the bytes of AscendArray&#39;s data
        _shape (tuple)   : the shape of this array
        _dtype (int)     : the acl data type of AscendArray
        _flag (int)      : the flag of defined memory malloc on device/host/dvpp
        _mem (instance)  : save the instance of class Memory()
        _data (a pointer): the mem ptr of AscendArray&#39;s data

    Attributes:
        ascend_data (int): Get(read) the pointer of data malloced by itself(_data&#39;s value), 
            or band it to a new memory.
        shape (tuple): Tuple of array dimensions. (should work with write ascend_data).
        ndim (int): Number of array dimensions.
        dtype (np.dtype): get or write the data type.
        size (int): Number of elements in the array.
        nbytes (int): Total bytes consumed by the elements of the array.
        itemsize (int): Length of one AscendArray element in bytes, which equal to size * dtype(size).
        flag (str): Information about the memory layout of the array.

    .. hint:: 
        - reshape   : Gives a new shape to an array without changing its data.
        - resize    : Return a new array with the specified shape.
        - to_np     : Use this function to copy device data to host and formal like numpy array.
        - to_ascend : trans a ndarray data to AscendArray(i.e. feed this instance with a numpy array data).
        - clone     : new a AscendArray object clone from np.ndarray
        - to        : copy this instance&#39;s data to another same shape AscendArray.
        - astype    : Copy of the array, cast to a specified type.
        - transpose : Reverse or permute the axes of an array; returns the modified array.
    &#34;&#34;&#34;

    def __init__(self, shape, dtype, size=0, buffer=None, format=None, context=None, flag=&#39;DEVICE&#39;):
        assert isinstance(shape, tuple), \
            f&#39;Input shape of AscendArray instance expects tuple, but got {type(shape)}&#39;

        try:
            self._dtype = np.dtype(dtype)
        except:
            raise TypeError(
                f&#39;Input dtype expect a numpy.dtype, but got {type(dtype)}&#39;)

        self._shape = shape
        self._flag = flag
        self._context = context
        self._format = format

        bind_context(context)

        is_malloc = True
        # calc memory size according to variable calling
        # 1. initial a scalar
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((), dtype=np.int32)
        if shape == ():
            self._nbytes = self._dtype.itemsize

        # 2. initial a array with shape(2, 3):
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((2, 3), dtype=np.float16)
        elif size &lt;= 0 and buffer is None:
            self._nbytes = int(np.prod(shape) * self._dtype.itemsize)

        # 3. initial a array with shape(6,) and 256 bytes
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((6,), dtype=np.float32, size=256)
        elif buffer is None:
            self._nbytes = size
            self._shape = (shape[0], size//(shape[0] * self._dtype.itemsize))

        # 4. initial a array with shape(16,) and binding memory pointer mem_ptr
        #    Examples:
        #    --------
        #    &gt;&gt;&gt; AscendArray((16,), dtype=np.float16, size=256, buffer=mem_ptr)
        else:
            self._nbytes = size
            self._shape = (shape[0], size//(shape[0] * self._dtype.itemsize))
            is_malloc = False

        # bind memory
        if is_malloc:
            self._mem = Memory(self._context, self._nbytes, flag)
            self._data = self._mem.ptr
        else:
            self._data = buffer

    # 1.ascend_data getter and setter
    @property
    def ascend_data(self): 
        return self._data

    @ascend_data.setter
    def ascend_data(self, dev_ptr: int):
        assert isinstance(dev_ptr, int), \
            f&#39;Function dev_ptr args of input expects int type, but got {type(dev_ptr)}&#39;

        if hasattr(self, &#39;_mem&#39;):
            del self._mem
        self._data = dev_ptr

    # 2.memory location getter
    @property
    def flag(self):
        return self._flag

    # 3.context resource getter and setter
    @property
    def context(self):
        return self._context

    @context.setter
    def context(self, context):
        &#34;&#34;&#34;Binding AscendArray with a new context.

        .. warning::
            Only support the memory of AscendArray create by itself.

        Args:
            context : the context to be binded.

        Returns:
            None.
        &#34;&#34;&#34;
        assert isinstance(context, int), \
            f&#34;Input context expects int value, but got {type(context)}.&#34;

        if not hasattr(self, &#39;_mem&#39;):
            raise ValueError(
                f&#34;This AscendArray instance not support to set context.&#34;)
        else:
            del self._mem

        bind_context(context)
        self._mem = Memory(context, self._nbytes, self._flag)
        self._data = self._mem.ptr

    # 4.ndim getter
    @property
    def ndim(self):
        return len(self._shape)

    # 5.shape getter and setter
    @property
    def shape(self):
        return self._shape

    @shape.setter
    def shape(self, shape):
        assert isinstance(shape, tuple), \
            f&#39;Input shape expects a tuple, but got {type(shape)}&#39;

        if len(shape) &lt;= 0 or shape[0] == 0:
            raise ValueError(
                &#39;Input shape is empty or format is invalid in calling function shape&#39;)

        self._shape = shape

    # 6.dtype getter and setter
    @property
    def dtype(self):
        return self._dtype

    @dtype.setter
    def dtype(self, dtype):
        try:
            self._dtype = np.dtype(dtype)
        except:
            raise TypeError(
                f&#39;Input dtype expects a numpy.dtype, but got {type(dtype)}&#39;)

    # 7.nbytes getter
    @property
    def nbytes(self):
        return self._nbytes

    # 8.itemsize getter
    @property
    def itemsize(self):
        return self._dtype.itemsize

    # 9.data format
    @property
    def format(self):
        return self._format

    @format.setter
    def format(self, format):
        if not isinstance(format, (str, int)):
            raise TypeError(
                f&#34;Input format expects int or string, but got {type(format)}.&#34;)

        self._format = format

    @property
    def size(self):
        return np.prod(self._shape)

    def reshape(self, shape):
        &#34;&#34;&#34;Gives a new shape to an array without changing its data.

        .. Note::
            Only modify the view of AscendArray.
            
        Args:
            shape (tuple[int]): Input new shape to be reshaped. It should be compatible with 
                the original shape.

        Returns:
            [AscendArray] : The original object with new shape.
        
        Typical usage example:
        ```python
        array = np.random.random(36*64).astype(&#39;float32&#39;).reshape(36, 64)
        ascend_array = ascend.AscendArray.clone(array)
        ascend_array = ascend_array.reshape(64, 36)
        ```
        &#34;&#34;&#34;
        assert isinstance(shape, tuple), \
            f&#39;Input shape expects tuple type, but got {type(shape)}.&#39;

        assert np.prod(self._shape) == np.prod(shape), \
            f&#34;The given shape({shape})&#39;s elements should same to {self._shape}.&#34;

        self._shape = shape
        return self

    def resize(self, shape: tuple):
        &#34;&#34;&#34;Resize the shape and data of AscendArray.

        .. Note::
            The data arrangement of AscendArray is modified.

        Args:
            shape (tuple): The resized new shape.

        Returns:
            [AscendArray] : The new object with a new shape.
        &#34;&#34;&#34;
        assert isinstance(shape, tuple), \
            f&#39;Input args of func reshape expects tuple type, but got {type(shape)}.&#39;

        pass

    def to_numpy(self, nbytes=None):
        &#34;&#34;&#34;Copy the attributes and data of AscendArray to np.ndarry object.

        Args:
            nbytes (int, optional): The data size of this object to be transformed. Defaults to None.

        Returns:
            [ndarray]: A copyed np.ndarray object

        Typical usage example:
        ```python
        array = np.random.random(3264)
        ascend_array = ascend.AscendArray.clone(array)
        data = ascend_array.to_numpy()
        ```
        &#34;&#34;&#34;
        if self._data is None:
            raise ValueError(&#39;Variable self._data is None in calling function to_np, \
                maybe this AscendArray instance parameter is null.&#39;)

        if nbytes and nbytes &gt; self._nbytes:
            raise ValueError(
                f&#34;Input nbytes must lower than {self._nbytes}, but got {nbytes}.&#34;)

        if self._flag != &#39;HOST&#39;:
            _nbytes = nbytes if nbytes else self._nbytes

            # copy device data to host
            cloned_array = AscendArray(shape=self._shape, dtype=self._dtype, format=self._format,
                                       context=self._context, flag=&#39;HOST&#39;)
            memcpy_d2h(cloned_array.ascend_data, self._data, _nbytes)
            numpy_ptr = cloned_array.ascend_data
        else:
            numpy_ptr = self._data

        try:
            np_type = const.numpy_dict[self._dtype]
        except KeyError:
            raise ValueError(
                f&#34;Convert AscendArray data to numpy not support this type {self._dtype}.&#34;)

        array = acl.util.ptr_to_numpy(numpy_ptr, self._shape, np_type)

        return array.copy()

    @property
    def to_np(self):
        return self.to_numpy()

    def to_ascend(self, array):
        &#34;&#34;&#34;Copy all the data of array(np.ndarray) to AscendArray.

        Args:
            array (np.ndarray): Input np.ndarray to be copyed.

        Typical usage example:
        ```python
        array = np.ones(shape=(384, 384), dtype=&#39;float16&#39;)
        ascend_array = AscendArray(shape=(384, 384), nbytes=array.nbytes, dtype=NPY_USHORT)
        ascend_array.to_ascend(array)
        ```
        &#34;&#34;&#34;
        if self._data is None:
            raise ValueError(&#39;instance arg self._data is None in calling function to_ascend, \
                Maybe this AscendArray instance parameter is null.&#39;)

        if self._flag == &#39;HOST&#39;:
            raise ValueError(
                f&#39;Method to_ascend only be used with DEVICE or DVPP memory&#39;)

        assert isinstance(array, np.ndarray), \
            f&#39;Function to_ascend args of input expects a np.ndarray object, but got {type(array)}&#39;

        assert (array.shape == self._shape) and (array.nbytes == self._nbytes), \
            &#39;Function to_ascend of input expects same shape and nbytes,&#39; \
            f&#39; but actually we got shape:{array.shape}, nbytes:{array.nbytes}.&#39;

        # get the array pointer for copy data to device
        array_ptr = acl.util.numpy_to_ptr(array)

        # do copy
        memcpy_h2d(self._data, array_ptr, self._nbytes)

    def astype(self, dtype):
        &#34;&#34;&#34; Cast a tensor from src data type to dst data type. Firstly, we try to use Cast operator 
            to release this function. If it fails, we use numpy astype method. 
        Args:
            dtype (np.dtype): The data type to be transformed.

        Returns:
            [AscendArray]: The new AscendArray data object.

        Typical usage example:
        ```python
        array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
        ascend_array = ascend.AscendArray.clone(array)
        ascend_array = ascend_array.astype(np.float16)
        ```
        &#34;&#34;&#34;
        try:
            from ..ops.op import Cast
            return Cast(self, dtype=dtype, context=self.context).data
        except:
            array = self.to_np.astype(dtype)
            return self.clone(array)

    def transpose(self, axes=None):
        &#34;&#34;&#34;Reverse or permute the axes of an array, and returns the modified array.

        Args:
            axes ([tuple, list], optional): Permute the axes of array. Defaults to None.

        Returns:
            [AscendArray]: A tranposed AscendArray.

        Typical usage example:
        ```python
        array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
        ascend_array = ascend.AscendArray.clone(array)
        ascend_array = ascend_array.astype(np.float16)
        ```
        &#34;&#34;&#34;
        if not isinstance(axes, (tuple, list)):
            raise TypeError(
                f&#34;Input axis expects a tuple or list, but got {type(axes)}.&#34;)

        try:
            from ..ops.op import Permute
            return Permute(self, axes=axes).data
        except:
            return np.transpose(self.to_np, axes=axes)

    @classmethod
    def clone(cls, array, context=None, format=None, flag=&#34;DEVICE&#34;):
        &#34;&#34;&#34;New an AscendArray object and clone all the attributes of array(np.ndarray) to it.

        Args:
            array (np.ndarray): A np.ndarray data to be cloned
            context (int, optional): The context resource working on. Defaults to None.
            format (data_format, optional): The cloned AscendArray data format, it should be &#39;NCHW&#39; 
                or &#39;NHWC&#39; for tensor, or it will be Ascend image format. Defaults to None.
            flag (str, optional): The Ascendarray memory flag, and it same to Ascend.Memory class. 
                Defaults to &#34;DEVICE&#34;.

        Raises:
            TypeError: The input array is not the intance of np.ndarray

        Returns:
            [AscendArray]: A cloned AscendArray object.

        Typical usage example:
        ```python
        array = np.random.random(644)
        data = ascend.AscendArray.clone(array)
        ```
        &#34;&#34;&#34;        
        assert isinstance(array, np.ndarray), \
            f&#39;Input args array expects class np.ndarray object, but got {type(array)}.&#39;

        if context and not isinstance(context, int):
            raise TypeError(
                f&#34;Input context expects int type, but got {type(context)}.&#34;)

        bind_context(context)

        # get the array pointer for copy device data to host
        array_ptr = acl.util.numpy_to_ptr(array)

        # new an AscendArray object shape like input array.
        cloned_array = cls(shape=array.shape, dtype=array.dtype,
                           format=format, context=context, flag=flag)

        # do copy
        memcpy_h2d(cloned_array.ascend_data, array_ptr, array.nbytes)

        return cloned_array

    def to(self, ascendarray):
        &#34;&#34;&#34;Copy this AscendArray data to another ascendarray(AscendArray).

        Args:
            ascendarray (AscendArray): The dst AscendArray to be assigned

        Typical usage example:
        ```python
        array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
        ascend_array1 = ascend.AscendArray.clone(array)
        ascend_array2 = ascend.AscendArray((128, 32), dtype=np.float32)
        ascend_array1.to(ascend_array2)
        ```
        &#34;&#34;&#34;
        if self._data is None:
            raise ValueError(&#34;Variable self._data is None in calling function &#39;to&#39;, \
                Maybe this AscendArray instance parameter is null.&#34;)

        assert isinstance(ascendarray, AscendArray), \
            f&#34;Input args of func &#39;to&#39; expects a class of AscendArray, but got {type(array)}.&#34;

        assert (self._nbytes &lt;= ascendarray.nbytes) and (self._dtype == ascendarray.dtype), \
            &#34;Shape or dtype of the input AscendArray is different from original.&#34;

        memcpy_d2d(ascendarray.ascend_data, self._data, self._nbytes)

    def __len__(self):
        &#34;&#34;&#34; Number of elements in the array, same to self.size.
        Args:
            None

        Returns:
            number of elements
        &#34;&#34;&#34;
        return np.prod(self._shape)

    def __getitem__(self, idx):
        &#34;&#34;&#34; get AscendArray data using subscript index
        Args:
            idx : an int or slice object

        Returns:
            data of AscendArray
        &#34;&#34;&#34;
        if self.dtype not in [
            np.dtype(&#39;float32&#39;),
            np.dtype(&#39;int8&#39;),
            np.dtype(&#39;int32&#39;),
            np.dtype(&#39;uint8&#39;)
        ]:
            raise TypeError(&#34;Only dtype in [&#39;float32&#39;, &#39;int32&#39;, &#39;int8&#39;, &#39;uint8&#39;] are support \
                            to using subscript index.&#34;)

        if not hasattr(self, &#39;_cloned_array&#39;):
            self._cloned_array = self.to_np
            self._cloned_array.reshape(self._shape)

        if isinstance(idx, int):
            if idx &lt; self.size and idx &gt;= 0:
                return self._cloned_array[idx]
            elif idx &gt; -self.size and idx &lt; 0:
                return self._cloned_array[idx + self.size]
            else:
                raise IndexError(f&#34;index {idx} is out of bounds for axis 0&#34;)

        elif isinstance(idx, slice):
            return self._cloned_array[idx]
        else:
            return &#39;index error&#39;

    def __setitem__(self, index, value):
        &#34;&#34;&#34; release to set AscendArray data using subscript index
        Args:
            idx : an int or slice object

        Returns:
            data of AscendArray
        &#34;&#34;&#34;
        import pdb
        pdb.set_trace()
        if not hasattr(self, &#39;_cloned_array&#39;):
            self._cloned_array = self.to_np

        if isinstance(index, int) and index &lt; self.size:
            self._cloned_array[index] = value
        elif isinstance(index, (list, tuple)):
            for i in index:
                assert i &lt; self.size, f&#39;index out of range.&#39;
            if isinstance(value, (list, tuple)):
                if len(index) == len(value):
                    for i, v in enumerate(index):
                        self._cloned_array[v] = value[i]
                else:
                    raise Exception(
                        &#39;values and index must be of the same length&#39;)
            elif isinstance(value, (int, float, str)):
                for i in index:
                    self._cloned_array[i] = value
            else:
                raise Exception(&#39;value error&#39;)
        else:
            raise Exception(&#39;index error&#39;)

        # update to device, it has lower performance for always write
        self.to_ascend(self._cloned_array)

    def __repr__(self):
        &#34;&#34;&#34; release to represent AscendArray data
        Args:
            None

        Returns:
            repr
        &#34;&#34;&#34;
        repr = &#34;ascendarray(\n{0}, dtype={1})&#34;.format(self.to_np, self.dtype)
        return repr

    def __del__(self):
        if hasattr(self, &#39;_mem&#39;):
            del self._mem
            self._data = None
        elif hasattr(self, &#39;_data&#39;) and self._data is not None:
            free(self._data, flag=self._flag)</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="ascend.AscendArray.clone"><code class="name flex">
<span>def <span class="ident">clone</span></span>(<span>array, context=None, format=None, flag='DEVICE')</span>
</code></dt>
<dd>
<div class="desc"><p>New an AscendArray object and clone all the attributes of array(np.ndarray) to it.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>array</code></strong> :&ensp;<code>np.ndarray</code></dt>
<dd>A np.ndarray data to be cloned</dd>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>The context resource working on. Defaults to None.</dd>
<dt><strong><code>format</code></strong> :&ensp;<code>data_format</code>, optional</dt>
<dd>The cloned AscendArray data format, it should be 'NCHW'
or 'NHWC' for tensor, or it will be Ascend image format. Defaults to None.</dd>
<dt><strong><code>flag</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The Ascendarray memory flag, and it same to Ascend.Memory class.
Defaults to "DEVICE".</dd>
</dl>
<h2 id="raises">Raises</h2>
<dl>
<dt><code>TypeError</code></dt>
<dd>The input array is not the intance of np.ndarray</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code></dt>
<dd>A cloned AscendArray object.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(644)
data = ascend.AscendArray.clone(array)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L400-L443" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@classmethod
def clone(cls, array, context=None, format=None, flag=&#34;DEVICE&#34;):
    &#34;&#34;&#34;New an AscendArray object and clone all the attributes of array(np.ndarray) to it.

    Args:
        array (np.ndarray): A np.ndarray data to be cloned
        context (int, optional): The context resource working on. Defaults to None.
        format (data_format, optional): The cloned AscendArray data format, it should be &#39;NCHW&#39; 
            or &#39;NHWC&#39; for tensor, or it will be Ascend image format. Defaults to None.
        flag (str, optional): The Ascendarray memory flag, and it same to Ascend.Memory class. 
            Defaults to &#34;DEVICE&#34;.

    Raises:
        TypeError: The input array is not the intance of np.ndarray

    Returns:
        [AscendArray]: A cloned AscendArray object.

    Typical usage example:
    ```python
    array = np.random.random(644)
    data = ascend.AscendArray.clone(array)
    ```
    &#34;&#34;&#34;        
    assert isinstance(array, np.ndarray), \
        f&#39;Input args array expects class np.ndarray object, but got {type(array)}.&#39;

    if context and not isinstance(context, int):
        raise TypeError(
            f&#34;Input context expects int type, but got {type(context)}.&#34;)

    bind_context(context)

    # get the array pointer for copy device data to host
    array_ptr = acl.util.numpy_to_ptr(array)

    # new an AscendArray object shape like input array.
    cloned_array = cls(shape=array.shape, dtype=array.dtype,
                       format=format, context=context, flag=flag)

    # do copy
    memcpy_h2d(cloned_array.ascend_data, array_ptr, array.nbytes)

    return cloned_array</code></pre>
</details>
</dd>
</dl>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.AscendArray.ascend_data"><code class="name">var <span class="ident">ascend_data</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L112-L114" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def ascend_data(self): 
    return self._data</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.context"><code class="name">var <span class="ident">context</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L131-L133" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def context(self):
    return self._context</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.dtype"><code class="name">var <span class="ident">dtype</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L183-L185" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def dtype(self):
    return self._dtype</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.flag"><code class="name">var <span class="ident">flag</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L126-L128" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def flag(self):
    return self._flag</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.format"><code class="name">var <span class="ident">format</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L206-L208" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def format(self):
    return self._format</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.itemsize"><code class="name">var <span class="ident">itemsize</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L201-L203" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def itemsize(self):
    return self._dtype.itemsize</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.nbytes"><code class="name">var <span class="ident">nbytes</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L196-L198" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def nbytes(self):
    return self._nbytes</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.ndim"><code class="name">var <span class="ident">ndim</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L162-L164" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def ndim(self):
    return len(self._shape)</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.shape"><code class="name">var <span class="ident">shape</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L167-L169" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def shape(self):
    return self._shape</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.size"><code class="name">var <span class="ident">size</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L218-L220" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def size(self):
    return np.prod(self._shape)</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.to_np"><code class="name">var <span class="ident">to_np</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L313-L315" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def to_np(self):
    return self.to_numpy()</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.AscendArray.astype"><code class="name flex">
<span>def <span class="ident">astype</span></span>(<span>self, dtype)</span>
</code></dt>
<dd>
<div class="desc"><p>Cast a tensor from src data type to dst data type. Firstly, we try to use Cast operator
to release this function. If it fails, we use numpy astype method. </p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>dtype</code></strong> :&ensp;<code>np.dtype</code></dt>
<dd>The data type to be transformed.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code></dt>
<dd>The new AscendArray data object.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(64*64).astype('float32').reshape(64, 64)
ascend_array = ascend.AscendArray.clone(array)
ascend_array = ascend_array.astype(np.float16)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L351-L372" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def astype(self, dtype):
    &#34;&#34;&#34; Cast a tensor from src data type to dst data type. Firstly, we try to use Cast operator 
        to release this function. If it fails, we use numpy astype method. 
    Args:
        dtype (np.dtype): The data type to be transformed.

    Returns:
        [AscendArray]: The new AscendArray data object.

    Typical usage example:
    ```python
    array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
    ascend_array = ascend.AscendArray.clone(array)
    ascend_array = ascend_array.astype(np.float16)
    ```
    &#34;&#34;&#34;
    try:
        from ..ops.op import Cast
        return Cast(self, dtype=dtype, context=self.context).data
    except:
        array = self.to_np.astype(dtype)
        return self.clone(array)</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.reshape"><code class="name flex">
<span>def <span class="ident">reshape</span></span>(<span>self, shape)</span>
</code></dt>
<dd>
<div class="desc"><p>Gives a new shape to an array without changing its data.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Only modify the view of AscendArray.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple[int]</code></dt>
<dd>Input new shape to be reshaped. It should be compatible with
the original shape.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>] </code></dt>
<dd>The original object with new shape.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(36*64).astype('float32').reshape(36, 64)
ascend_array = ascend.AscendArray.clone(array)
ascend_array = ascend_array.reshape(64, 36)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L222-L249" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def reshape(self, shape):
    &#34;&#34;&#34;Gives a new shape to an array without changing its data.

    .. Note::
        Only modify the view of AscendArray.
        
    Args:
        shape (tuple[int]): Input new shape to be reshaped. It should be compatible with 
            the original shape.

    Returns:
        [AscendArray] : The original object with new shape.
    
    Typical usage example:
    ```python
    array = np.random.random(36*64).astype(&#39;float32&#39;).reshape(36, 64)
    ascend_array = ascend.AscendArray.clone(array)
    ascend_array = ascend_array.reshape(64, 36)
    ```
    &#34;&#34;&#34;
    assert isinstance(shape, tuple), \
        f&#39;Input shape expects tuple type, but got {type(shape)}.&#39;

    assert np.prod(self._shape) == np.prod(shape), \
        f&#34;The given shape({shape})&#39;s elements should same to {self._shape}.&#34;

    self._shape = shape
    return self</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.resize"><code class="name flex">
<span>def <span class="ident">resize</span></span>(<span>self, shape: tuple)</span>
</code></dt>
<dd>
<div class="desc"><p>Resize the shape and data of AscendArray.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The data arrangement of AscendArray is modified.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple</code></dt>
<dd>The resized new shape.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>] </code></dt>
<dd>The new object with a new shape.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L251-L266" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def resize(self, shape: tuple):
    &#34;&#34;&#34;Resize the shape and data of AscendArray.

    .. Note::
        The data arrangement of AscendArray is modified.

    Args:
        shape (tuple): The resized new shape.

    Returns:
        [AscendArray] : The new object with a new shape.
    &#34;&#34;&#34;
    assert isinstance(shape, tuple), \
        f&#39;Input args of func reshape expects tuple type, but got {type(shape)}.&#39;

    pass</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.to"><code class="name flex">
<span>def <span class="ident">to</span></span>(<span>self, ascendarray)</span>
</code></dt>
<dd>
<div class="desc"><p>Copy this AscendArray data to another ascendarray(AscendArray).</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>ascendarray</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The dst AscendArray to be assigned</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(64*64).astype('float32').reshape(64, 64)
ascend_array1 = ascend.AscendArray.clone(array)
ascend_array2 = ascend.AscendArray((128, 32), dtype=np.float32)
ascend_array1.to(ascend_array2)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L445-L469" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def to(self, ascendarray):
    &#34;&#34;&#34;Copy this AscendArray data to another ascendarray(AscendArray).

    Args:
        ascendarray (AscendArray): The dst AscendArray to be assigned

    Typical usage example:
    ```python
    array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
    ascend_array1 = ascend.AscendArray.clone(array)
    ascend_array2 = ascend.AscendArray((128, 32), dtype=np.float32)
    ascend_array1.to(ascend_array2)
    ```
    &#34;&#34;&#34;
    if self._data is None:
        raise ValueError(&#34;Variable self._data is None in calling function &#39;to&#39;, \
            Maybe this AscendArray instance parameter is null.&#34;)

    assert isinstance(ascendarray, AscendArray), \
        f&#34;Input args of func &#39;to&#39; expects a class of AscendArray, but got {type(array)}.&#34;

    assert (self._nbytes &lt;= ascendarray.nbytes) and (self._dtype == ascendarray.dtype), \
        &#34;Shape or dtype of the input AscendArray is different from original.&#34;

    memcpy_d2d(ascendarray.ascend_data, self._data, self._nbytes)</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.to_ascend"><code class="name flex">
<span>def <span class="ident">to_ascend</span></span>(<span>self, array)</span>
</code></dt>
<dd>
<div class="desc"><p>Copy all the data of array(np.ndarray) to AscendArray.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>array</code></strong> :&ensp;<code>np.ndarray</code></dt>
<dd>Input np.ndarray to be copyed.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.ones(shape=(384, 384), dtype='float16')
ascend_array = AscendArray(shape=(384, 384), nbytes=array.nbytes, dtype=NPY_USHORT)
ascend_array.to_ascend(array)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L317-L349" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def to_ascend(self, array):
    &#34;&#34;&#34;Copy all the data of array(np.ndarray) to AscendArray.

    Args:
        array (np.ndarray): Input np.ndarray to be copyed.

    Typical usage example:
    ```python
    array = np.ones(shape=(384, 384), dtype=&#39;float16&#39;)
    ascend_array = AscendArray(shape=(384, 384), nbytes=array.nbytes, dtype=NPY_USHORT)
    ascend_array.to_ascend(array)
    ```
    &#34;&#34;&#34;
    if self._data is None:
        raise ValueError(&#39;instance arg self._data is None in calling function to_ascend, \
            Maybe this AscendArray instance parameter is null.&#39;)

    if self._flag == &#39;HOST&#39;:
        raise ValueError(
            f&#39;Method to_ascend only be used with DEVICE or DVPP memory&#39;)

    assert isinstance(array, np.ndarray), \
        f&#39;Function to_ascend args of input expects a np.ndarray object, but got {type(array)}&#39;

    assert (array.shape == self._shape) and (array.nbytes == self._nbytes), \
        &#39;Function to_ascend of input expects same shape and nbytes,&#39; \
        f&#39; but actually we got shape:{array.shape}, nbytes:{array.nbytes}.&#39;

    # get the array pointer for copy data to device
    array_ptr = acl.util.numpy_to_ptr(array)

    # do copy
    memcpy_h2d(self._data, array_ptr, self._nbytes)</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.to_numpy"><code class="name flex">
<span>def <span class="ident">to_numpy</span></span>(<span>self, nbytes=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Copy the attributes and data of AscendArray to np.ndarry object.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>nbytes</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>The data size of this object to be transformed. Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[ndarray]</code></dt>
<dd>A copyed np.ndarray object</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(3264)
ascend_array = ascend.AscendArray.clone(array)
data = ascend_array.to_numpy()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L268-L311" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def to_numpy(self, nbytes=None):
    &#34;&#34;&#34;Copy the attributes and data of AscendArray to np.ndarry object.

    Args:
        nbytes (int, optional): The data size of this object to be transformed. Defaults to None.

    Returns:
        [ndarray]: A copyed np.ndarray object

    Typical usage example:
    ```python
    array = np.random.random(3264)
    ascend_array = ascend.AscendArray.clone(array)
    data = ascend_array.to_numpy()
    ```
    &#34;&#34;&#34;
    if self._data is None:
        raise ValueError(&#39;Variable self._data is None in calling function to_np, \
            maybe this AscendArray instance parameter is null.&#39;)

    if nbytes and nbytes &gt; self._nbytes:
        raise ValueError(
            f&#34;Input nbytes must lower than {self._nbytes}, but got {nbytes}.&#34;)

    if self._flag != &#39;HOST&#39;:
        _nbytes = nbytes if nbytes else self._nbytes

        # copy device data to host
        cloned_array = AscendArray(shape=self._shape, dtype=self._dtype, format=self._format,
                                   context=self._context, flag=&#39;HOST&#39;)
        memcpy_d2h(cloned_array.ascend_data, self._data, _nbytes)
        numpy_ptr = cloned_array.ascend_data
    else:
        numpy_ptr = self._data

    try:
        np_type = const.numpy_dict[self._dtype]
    except KeyError:
        raise ValueError(
            f&#34;Convert AscendArray data to numpy not support this type {self._dtype}.&#34;)

    array = acl.util.ptr_to_numpy(numpy_ptr, self._shape, np_type)

    return array.copy()</code></pre>
</details>
</dd>
<dt id="ascend.AscendArray.transpose"><code class="name flex">
<span>def <span class="ident">transpose</span></span>(<span>self, axes=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Reverse or permute the axes of an array, and returns the modified array.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>axes</code></strong> :&ensp;<code>[tuple, list]</code>, optional</dt>
<dd>Permute the axes of array. Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code></dt>
<dd>A tranposed AscendArray.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">array = np.random.random(64*64).astype('float32').reshape(64, 64)
ascend_array = ascend.AscendArray.clone(array)
ascend_array = ascend_array.astype(np.float16)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/data/ascendarray.py#L374-L398" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def transpose(self, axes=None):
    &#34;&#34;&#34;Reverse or permute the axes of an array, and returns the modified array.

    Args:
        axes ([tuple, list], optional): Permute the axes of array. Defaults to None.

    Returns:
        [AscendArray]: A tranposed AscendArray.

    Typical usage example:
    ```python
    array = np.random.random(64*64).astype(&#39;float32&#39;).reshape(64, 64)
    ascend_array = ascend.AscendArray.clone(array)
    ascend_array = ascend_array.astype(np.float16)
    ```
    &#34;&#34;&#34;
    if not isinstance(axes, (tuple, list)):
        raise TypeError(
            f&#34;Input axis expects a tuple or list, but got {type(axes)}.&#34;)

    try:
        from ..ops.op import Permute
        return Permute(self, axes=axes).data
    except:
        return np.transpose(self.to_np, axes=axes)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.AscendModel"><code class="flex name class">
<span>class <span class="ident">AscendModel</span></span>
<span>(</span><span>context, model_path)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a AscendModel class like to manage model and inferring.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code></dt>
<dd>Context resource of this model working on.</dd>
<dt><strong><code>stream</code></strong> :&ensp;<code>int</code></dt>
<dd>Stream resource of this model working on.</dd>
<dt><strong><code>model_id</code></strong> :&ensp;<code>int</code></dt>
<dd>This model's id</dd>
<dt><strong><code>tensor</code></strong> :&ensp;<code>dict</code></dt>
<dd>A ordered-dict to save all input and output tensors</dd>
<dt><strong><code>net_in_n</code></strong> :&ensp;<code>int</code></dt>
<dd>Model's input numbers</dd>
<dt><strong><code>net_out_n</code></strong> :&ensp;<code>int</code></dt>
<dd>Model's output numbers</dd>
<dt><strong><code>dataset_in</code></strong> :&ensp;<code>DataSet obj</code></dt>
<dd>Input dataset object of model</dd>
<dt><strong><code>dataset_out</code></strong> :&ensp;<code>DataSet obj</code></dt>
<dd>Output dataset object of model</dd>
<dt><strong><code>tensor_names</code></strong> :&ensp;<code>str</code></dt>
<dd>Model's input and output tensors' name.</dd>
</dl>
<div class="admonition hint">
<p class="admonition-title">Hint</p>
<ul>
<li>run
: do model inference</li>
<li>feed_data
: feed AscendArray data to model's input port</li>
<li>get_tensor_by_name : get the output result of inference according to output tensor name</li>
<li>set_batch
: Set model input dynamic batch size.</li>
<li>set_shape
: Set model input dynamic shape.</li>
</ul>
</div>
<p>Typical usage example:</p>
<pre><code class="language-python">model = ascend.AscendModel(context, model_path='./yolov3.om')
print(model.tensor_names)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L102-L488" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class AscendModel():
    &#34;&#34;&#34;Define a AscendModel class like to manage model and inferring.

    Attributes:
        context (int): Context resource of this model working on.
        stream (int): Stream resource of this model working on.
        model_id (int): This model&#39;s id
        tensor (dict): A ordered-dict to save all input and output tensors
        net_in_n (int): Model&#39;s input numbers
        net_out_n (int): Model&#39;s output numbers
        dataset_in (DataSet obj): Input dataset object of model
        dataset_out (DataSet obj): Output dataset object of model
        tensor_names (str): Model&#39;s input and output tensors&#39; name.

    .. hint:: 
        - run                : do model inference
        - feed_data          : feed AscendArray data to model&#39;s input port
        - get_tensor_by_name : get the output result of inference according to output tensor name
        - set_batch          : Set model input dynamic batch size.
        - set_shape          : Set model input dynamic shape.

    Typical usage example:
    ```python
    model = ascend.AscendModel(context, model_path=&#39;./yolov3.om&#39;)
    print(model.tensor_names)
    ```
    &#34;&#34;&#34;
    def __init__(self,
                context,
                model_path):
        self.class_name = self.__class__.__name__
        self.context = context
        self.stream = create_stream(context)

        self.tensor = OrderedDict()
        self.net_in_n = 0
        self.net_out_n = 0
        self.dataset_in = None
        self.dataset_out = None
        self._tensor_names = {&#39;input&#39;:[], &#39;output&#39;:[]}

        # load model and initial
        self.__load_model(model_path)

    def __load_model(self, model_path:str):
        &#34;&#34;&#34;load model and create input and output tensor.
        Args:
            model_path.

        Returns:
            None.
        &#34;&#34;&#34;
        if not isinstance(model_path, str):
            raise TypeError(&#39;model_path must be a string. &#39;
                        f&#39;But received {type(model_path)}&#39;)

        self.model_id, ret = acl.mdl.load_from_file(model_path)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#39;Failed to load model from file {model_path}, return {ret}.&#39;)

        # creating the model instance, which only be created once.
        self.__model_desc = ModelDesc(self.model_id)

        self.net_in_n = acl.mdl.get_num_inputs(self.__model_desc.desc)
        if self.net_in_n &lt;= 0:
            raise ValueError(&#39;input num of model should larger than 0. &#39;
                        f&#39;But received {self.net_in_n}&#39;)

        self.net_out_n = acl.mdl.get_num_outputs(self.__model_desc.desc)
        if self.net_out_n &lt;= 0:
            raise ValueError(&#39;output num of model should larger than 0. &#39;
                        f&#39;But received {self.net_out_n}&#39;)

        self.__create_input_tensor(self.__model_desc.desc, self.net_in_n)
        Log(INFO, &#39;create input tensor success.&#39;)

        self.__create_output_tensor(self.__model_desc.desc, self.net_out_n)
        Log(INFO, &#39;create output tensor success.&#39;)

    def __create_input_tensor(self, model_desc, net_input_num:int):
        &#34;&#34;&#34;create input tensor and band memory pointer.
        Args:
            model_desc: model&#39;s information and description.
            net_input_num: input node number of the net.
        Returns:
            None.
        &#34;&#34;&#34;
        if model_desc is None:
            raise ValueError(&#39;Input param model_desc should not be None.&#39;)
        if not isinstance(net_input_num, int):
            raise TypeError(&#39;Input param net_input_num must be an int. &#39;
                    f&#39;But received {type(net_input_num)}&#39;)
        if net_input_num &lt;= 0:
            raise ValueError(&#39;Input param net_input_num should larger than 0. &#39;
                    f&#39;But received {net_input_num}&#39;)

        self.dataset_in = DataSet()
        Log(INFO, &#39; create input dataset success.&#39;)

        for idx in range(net_input_num):
            dims, ret = acl.mdl.get_input_dims_v2(model_desc, idx)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#39;Failed to get input dims at {idx} in func \
                        __create_input_tensor. Return value {ret}.&#39;)

            # get input acl tensor name and data type.
            tensor_name = dims[&#34;name&#34;]
            tensor_dtype = acl.mdl.get_input_data_type(model_desc, idx)
            tensor_format = acl.mdl.get_input_format(model_desc, idx)
            tensor_format = tensor_fmt_map[tensor_format]

            # create a tensor of class AscendArray and assign attributes to it.
            self.tensor[tensor_name] = AscendArray(shape=tuple(dims[&#34;dims&#34;]), dtype=dtype_dict[tensor_dtype], \
                                                    format=tensor_format)

            # banding the dataset with data buffer
            self.dataset_in.add_buffer(self.tensor[tensor_name])

            # save tensor name to input
            self._tensor_names[&#39;input&#39;].append(tensor_name)

        Log(INFO, &#39;create input tensor success.&#39;)

    def __create_output_tensor(self, model_desc, net_output_num):
        &#34;&#34;&#34;create output tensor and band memory pointer.
        Args:
            model_desc: model&#39;s information and description.
            net_output_num: output tensor number of the net.
        Returns:
            None.
        &#34;&#34;&#34;
        if model_desc is None:
            raise ValueError(&#39;Input param model_desc should not be None.&#39;)
        if not isinstance(net_output_num, int):
            raise TypeError(&#39;Input param net_output_num must be an int. &#39;
                    f&#39;But received {type(net_output_num)}&#39;)
        if net_output_num &lt;= 0:
            raise ValueError(&#39;Input param net_output_num should larger than 0. &#39;
                    f&#39;But received {net_output_num}&#39;)

        self.dataset_out = DataSet()
        Log(INFO, &#39; create output dataset success.&#39;)

        for idx in range(net_output_num):
            dims, ret = acl.mdl.get_output_dims(model_desc, idx)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#39;Failed to get output dims at {idx} in func \
                        __create_output_tensor. Return value {ret}.&#39;)

            # get the acl tensor name and data type.
            tensor_name = dims[&#34;name&#34;]
            tensor_dtype = acl.mdl.get_output_data_type(model_desc, idx)
            tensor_format = acl.mdl.get_output_format(model_desc, idx)
            tensor_format = tensor_fmt_map[tensor_format]
            
            # create a tensor of class AscendArray and assign attributes to it.
            self.tensor[tensor_name] = AscendArray(shape=tuple(dims[&#34;dims&#34;]), dtype=dtype_dict[tensor_dtype], \
                                                    format=tensor_format)

            # banding the dataset with data buffer
            self.dataset_out.add_buffer(self.tensor[tensor_name])

            # save tensor name to output
            self._tensor_names[&#39;output&#39;].append(tensor_name)

        Log(INFO, &#39;create output tensor success.&#39;)

    def __check_input(self, data, net_in):
        &#34;&#34;&#34; check input data is matched with model input
        Args:
            data   : input image or data.
            net_in : model input tensor

        Returns:
            None.
        &#34;&#34;&#34;
        if not isinstance(data, AscendArray):
            raise TypeError(f&#34;feed data expects an AscendArray, but got {type(data)}.&#34;)
            
        Log(INFO, f&#34;data format: {data.format}, net_in format: {net_in.format}.&#34;)

        # case 1: input yuv420_nv12 or yuv420_nv21 or yuv400 image
        if data.ndim == 2 and net_in.ndim != 2:
            # for single image/tensor, only judge channel is same to model input
            if (net_in.format == &#39;NCHW&#39; and net_in.shape[1] != 1) or \
                    (net_in.format == &#34;NHWC&#34; and net_in.shape[3] != 1):
                raise ValueError(
                    f&#34;Input tensor&#39;s expects a single channel with shape {net_in.shape}, but got {data.shape}.&#34;)

        # case 2: input RGB/BGR or 3-dims tensor
        if data.ndim == 3:
            # only judge channel is same to model input
            if (net_in.format == &#39;NCHW&#39; and net_in.shape[1] != 3) or \
                    (net_in.format == &#34;NHWC&#34; and net_in.shape[3] != 3):
                raise ValueError(
                    f&#34;Input tensor&#39;s expects a single channel with shape {net_in.shape}, but got {data.shape}.&#34;)

        # case 3: input 4-dims tensor
        if data.ndim == 4:
            assert data.shape == net_in.shape, \
                f&#34;Feed data expects same shape to model input {net_in.shape}, but got {data.shape}.&#34;

        # if elements of input data not equal to model input, print warnning log.
        if data.size != net_in.size:
            Log(WARNING, f&#34;feed data size {data.shape} not suit to model input {net_in.shape}.&#34;)

    def run(self):
        &#34;&#34;&#34;Run model offline inference.

        ```python
        # model is the instantiated AscendModel obj
        model.run()
        ```
        &#34;&#34;&#34;
        ret = acl.mdl.execute_async(
                        self.model_id,
                        self.dataset_in.dataset,
                        self.dataset_out.dataset,
                        self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to excute async in model inference, return {ret}.&#34;)
        
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in model inference, return {ret}.&#34;)

        Log(INFO, &#39;model inference success.&#39;)


    def feed_data(self, args:dict):
        &#34;&#34;&#34;Feed data to model.

        Args:
            args (dict): Feed specific tensor&#39;s data to the model.

        Typical usage example: 
        ```python
        # &#39;input_tensor*&#39; is the node of model input, and input_data* is the preprocessed data(image).
        model.feed_data({&#39;input_tensor1&#39;:input_data1, &#39;input_tensor2&#39;:input_data2})
        ```
        &#34;&#34;&#34;
        if not isinstance(args, dict):
            raise TypeError(f&#39;Input feed_data expects a dict, but received {type(args)}.&#39;)

        if len(args) &lt;= 0:
            raise TypeError(&#39;Input args of feed_data is null.&#39;)

        if len(args) != self.net_in_n:
            raise ValueError(&#39;Input tensor number to model should be equal to the net input number (&#39;
                f&#39;{self.net_in_n}). But the actual input is: {len(args)}&#39;)

        for key, in_tensor in args.items():
            assert (key in self.tensor), \
                f&#39;Tensor name {key} is not the input or this tensor name is not correct,&#39; \
                 + f&#39; you should choose one of {self._tensor_names}.&#39;

            # feed data process will separate to below steps:
            # step 1: check input data is matched with model input
            self.__check_input(in_tensor, self.tensor[key])

            # step 2:
            #   copy input tensor&#39;s data(the front module&#39;s output data) ptr to variable input_ptr, 
            #   while input_tensor_dict.values() is a class of AscendArray
            input_ptr = in_tensor.ascend_data

            # step 3:
            #   copy model input tensor&#39;s data ptr to variable tensor_ptr
            tensor_ptr = self.tensor[key].ascend_data

            # step 4:
            #   get data size that will be copy to model input dataset
            size = min(self.tensor[key].nbytes, in_tensor.nbytes)

            # step 5:
            #   do copy
            memcpy_d2d(tensor_ptr, input_ptr, size)

        Log(INFO, &#39;feed data to model success.&#39;)


    def get_tensor_by_name(self, out_node_name:str):
        &#34;&#34;&#34;Get tensor data from output of model inference.
        Args:
            out_node_name (str): Get specific tensor&#39;s data by name. 

        Returns:
            AscendArray: Output tensor of node out_node_name after model inference.

        Typical usage example: 
        ```python
        # &#39;output_tensor_name1&#39; and &#39;output_tensor_name2&#39; is the node of model output
        output_tensor1 = model.get_tensor_by_name(&#39;output_tensor_name1&#39;)
        output_tensor2 = model.get_tensor_by_name(&#39;output_tensor_name2&#39;)
        ```
        &#34;&#34;&#34;
        assert isinstance(out_node_name, str), \
                f&#39;Func args of get_tensor_by_name expects str type, but got {type(out_node_name)}&#39;
        
        assert (out_node_name in self.tensor), \
                f&#39;Tensor name [{out_node_name}] is not the output tensor or this tensor name is not correct,&#39; \
                 + f&#39; you should choose one of {self._tensor_names}.&#39;

        return self.tensor[out_node_name]
    
    @property
    def tensor_names(self):
        &#34;&#34;&#34;Get input and output tensors&#39; name from model.

        Returns:
            list: Input/output node&#39;s name of model.

        Typical usage example: 
        ```python
        #&#39;tensor_names&#39; is the node of model input and output.
        tensor_names = model.tensor_names
        ```
        &#34;&#34;&#34;
        return self._tensor_names


    def set_batch(self, tensor_name, batch):
        &#34;&#34;&#34;Set model input dynamic batch size.

        Args:
            tensor_name (str): Input tensor&#39;s name
            batch (int): Configurated tensor&#39;s batch size
        &#34;&#34;&#34;
        if not isinstance(batch, int):
            raise ValueError(f&#34;Input batch expects an int, but got {type(batch)}.&#34;)
        
        idx, ret = acl.mdl.get_input_index_by_name(self.__model_desc.desc, tensor_name)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Input tensor name {tensor_name} is not a input.&#34;)

        ret = acl.mdl.set_dynamic_batch_size(self.model_id, self.dataset_in, idx, batch)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;set dynamic batch size failed for input {idx}, return {ret}.&#34;)

    def set_shape(self, tensor_name, shape):
        &#34;&#34;&#34;Set model input dynamic shape.
        Args:
            shape (tuple): a tuple (w, h) of dynamic input shape

        Returns:
            None.
        &#34;&#34;&#34;
        if not isinstance(shape, tuple):
            raise ValueError(f&#34;Input shape expects an tuple, but got {type(shape)}.&#34;)
        
        idx, ret = acl.mdl.get_input_index_by_name(self.__model_desc.desc, tensor_name)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Input tensor name {tensor_name} is not a input.&#34;)

        ret = acl.mdl.set_dynamic_hw_size(self.model_id, self.dataset, idx, shape[1], shape[0])
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;set dynamic shape failed for input {idx}, return {ret}.&#34;)

    def __release_model(self):
        &#34;&#34;&#34;release data and unload model.
        Args:
            None

        Returns:
            None.
        &#34;&#34;&#34;
        if hasattr(self, &#39;__model_desc&#39;):
            del self.__model_desc

        if hasattr(self, &#39;model_id&#39;) and self.model_id:
            ret = acl.mdl.unload(self.model_id)
            assert ret == ACL_SUCCESS, f&#39;Unload model with id: {self.model_id} failded.&#39;

        if hasattr(self, &#39;stream&#39;):
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, \
                f&#34;destroy stream error in func __release_model, return {ret}.&#34;

        Log(INFO, &#39;release model success&#39;)

    def __del__(self):
        ctx, ret = acl.rt.get_context()
        if ret != ACL_SUCCESS or ctx is None:
            raise ValueError(&#34;Release AscendModel instance failed, because context is not available.&#34;)
             
        del self.dataset_in
        del self.dataset_out
        self.__release_model()</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.AscendModel.tensor_names"><code class="name">var <span class="ident">tensor_names</span></code></dt>
<dd>
<div class="desc"><p>Get input and output tensors' name from model.</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list</code></dt>
<dd>Input/output node's name of model.</dd>
</dl>
<p>Typical usage example: </p>
<pre><code class="language-python">#'tensor_names' is the node of model input and output.
tensor_names = model.tensor_names
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L406-L419" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def tensor_names(self):
    &#34;&#34;&#34;Get input and output tensors&#39; name from model.

    Returns:
        list: Input/output node&#39;s name of model.

    Typical usage example: 
    ```python
    #&#39;tensor_names&#39; is the node of model input and output.
    tensor_names = model.tensor_names
    ```
    &#34;&#34;&#34;
    return self._tensor_names</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.AscendModel.feed_data"><code class="name flex">
<span>def <span class="ident">feed_data</span></span>(<span>self, args: dict)</span>
</code></dt>
<dd>
<div class="desc"><p>Feed data to model.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>args</code></strong> :&ensp;<code>dict</code></dt>
<dd>Feed specific tensor's data to the model.</dd>
</dl>
<p>Typical usage example: </p>
<pre><code class="language-python"># 'input_tensor*' is the node of model input, and input_data* is the preprocessed data(image).
model.feed_data({'input_tensor1':input_data1, 'input_tensor2':input_data2})
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L331-L379" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def feed_data(self, args:dict):
    &#34;&#34;&#34;Feed data to model.

    Args:
        args (dict): Feed specific tensor&#39;s data to the model.

    Typical usage example: 
    ```python
    # &#39;input_tensor*&#39; is the node of model input, and input_data* is the preprocessed data(image).
    model.feed_data({&#39;input_tensor1&#39;:input_data1, &#39;input_tensor2&#39;:input_data2})
    ```
    &#34;&#34;&#34;
    if not isinstance(args, dict):
        raise TypeError(f&#39;Input feed_data expects a dict, but received {type(args)}.&#39;)

    if len(args) &lt;= 0:
        raise TypeError(&#39;Input args of feed_data is null.&#39;)

    if len(args) != self.net_in_n:
        raise ValueError(&#39;Input tensor number to model should be equal to the net input number (&#39;
            f&#39;{self.net_in_n}). But the actual input is: {len(args)}&#39;)

    for key, in_tensor in args.items():
        assert (key in self.tensor), \
            f&#39;Tensor name {key} is not the input or this tensor name is not correct,&#39; \
             + f&#39; you should choose one of {self._tensor_names}.&#39;

        # feed data process will separate to below steps:
        # step 1: check input data is matched with model input
        self.__check_input(in_tensor, self.tensor[key])

        # step 2:
        #   copy input tensor&#39;s data(the front module&#39;s output data) ptr to variable input_ptr, 
        #   while input_tensor_dict.values() is a class of AscendArray
        input_ptr = in_tensor.ascend_data

        # step 3:
        #   copy model input tensor&#39;s data ptr to variable tensor_ptr
        tensor_ptr = self.tensor[key].ascend_data

        # step 4:
        #   get data size that will be copy to model input dataset
        size = min(self.tensor[key].nbytes, in_tensor.nbytes)

        # step 5:
        #   do copy
        memcpy_d2d(tensor_ptr, input_ptr, size)

    Log(INFO, &#39;feed data to model success.&#39;)</code></pre>
</details>
</dd>
<dt id="ascend.AscendModel.get_tensor_by_name"><code class="name flex">
<span>def <span class="ident">get_tensor_by_name</span></span>(<span>self, out_node_name: str)</span>
</code></dt>
<dd>
<div class="desc"><p>Get tensor data from output of model inference.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>out_node_name</code></strong> :&ensp;<code>str</code></dt>
<dd>Get specific tensor's data by name. </dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Output tensor of node out_node_name after model inference.</dd>
</dl>
<p>Typical usage example: </p>
<pre><code class="language-python"># 'output_tensor_name1' and 'output_tensor_name2' is the node of model output
output_tensor1 = model.get_tensor_by_name('output_tensor_name1')
output_tensor2 = model.get_tensor_by_name('output_tensor_name2')
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L382-L404" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def get_tensor_by_name(self, out_node_name:str):
    &#34;&#34;&#34;Get tensor data from output of model inference.
    Args:
        out_node_name (str): Get specific tensor&#39;s data by name. 

    Returns:
        AscendArray: Output tensor of node out_node_name after model inference.

    Typical usage example: 
    ```python
    # &#39;output_tensor_name1&#39; and &#39;output_tensor_name2&#39; is the node of model output
    output_tensor1 = model.get_tensor_by_name(&#39;output_tensor_name1&#39;)
    output_tensor2 = model.get_tensor_by_name(&#39;output_tensor_name2&#39;)
    ```
    &#34;&#34;&#34;
    assert isinstance(out_node_name, str), \
            f&#39;Func args of get_tensor_by_name expects str type, but got {type(out_node_name)}&#39;
    
    assert (out_node_name in self.tensor), \
            f&#39;Tensor name [{out_node_name}] is not the output tensor or this tensor name is not correct,&#39; \
             + f&#39; you should choose one of {self._tensor_names}.&#39;

    return self.tensor[out_node_name]</code></pre>
</details>
</dd>
<dt id="ascend.AscendModel.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Run model offline inference.</p>
<pre><code class="language-python"># model is the instantiated AscendModel obj
model.run()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L308-L328" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34;Run model offline inference.

    ```python
    # model is the instantiated AscendModel obj
    model.run()
    ```
    &#34;&#34;&#34;
    ret = acl.mdl.execute_async(
                    self.model_id,
                    self.dataset_in.dataset,
                    self.dataset_out.dataset,
                    self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to excute async in model inference, return {ret}.&#34;)
    
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in model inference, return {ret}.&#34;)

    Log(INFO, &#39;model inference success.&#39;)</code></pre>
</details>
</dd>
<dt id="ascend.AscendModel.set_batch"><code class="name flex">
<span>def <span class="ident">set_batch</span></span>(<span>self, tensor_name, batch)</span>
</code></dt>
<dd>
<div class="desc"><p>Set model input dynamic batch size.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>tensor_name</code></strong> :&ensp;<code>str</code></dt>
<dd>Input tensor's name</dd>
<dt><strong><code>batch</code></strong> :&ensp;<code>int</code></dt>
<dd>Configurated tensor's batch size</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L422-L438" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def set_batch(self, tensor_name, batch):
    &#34;&#34;&#34;Set model input dynamic batch size.

    Args:
        tensor_name (str): Input tensor&#39;s name
        batch (int): Configurated tensor&#39;s batch size
    &#34;&#34;&#34;
    if not isinstance(batch, int):
        raise ValueError(f&#34;Input batch expects an int, but got {type(batch)}.&#34;)
    
    idx, ret = acl.mdl.get_input_index_by_name(self.__model_desc.desc, tensor_name)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Input tensor name {tensor_name} is not a input.&#34;)

    ret = acl.mdl.set_dynamic_batch_size(self.model_id, self.dataset_in, idx, batch)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;set dynamic batch size failed for input {idx}, return {ret}.&#34;)</code></pre>
</details>
</dd>
<dt id="ascend.AscendModel.set_shape"><code class="name flex">
<span>def <span class="ident">set_shape</span></span>(<span>self, tensor_name, shape)</span>
</code></dt>
<dd>
<div class="desc"><p>Set model input dynamic shape.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple</code></dt>
<dd>a tuple (w, h) of dynamic input shape</dd>
</dl>
<h2 id="returns">Returns</h2>
<p>None.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/model/model.py#L440-L457" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def set_shape(self, tensor_name, shape):
    &#34;&#34;&#34;Set model input dynamic shape.
    Args:
        shape (tuple): a tuple (w, h) of dynamic input shape

    Returns:
        None.
    &#34;&#34;&#34;
    if not isinstance(shape, tuple):
        raise ValueError(f&#34;Input shape expects an tuple, but got {type(shape)}.&#34;)
    
    idx, ret = acl.mdl.get_input_index_by_name(self.__model_desc.desc, tensor_name)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Input tensor name {tensor_name} is not a input.&#34;)

    ret = acl.mdl.set_dynamic_hw_size(self.model_id, self.dataset, idx, shape[1], shape[0])
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;set dynamic shape failed for input {idx}, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Cast"><code class="flex name class">
<span>class <span class="ident">Cast</span></span>
<span>(</span><span>input, dtype=dtype('float16'), context=None, stream=None)</span>
</code></dt>
<dd>
<div class="desc"><p>define a Cast operator object to release dtype convert. support translate types:
float -&gt; float16, float16 -&gt; float, uint8 -&gt; float16, float16 -&gt; uint8
uint8 -&gt; float32, float32 -&gt; uint8, float16 -&gt; int32, int32 -&gt; float16
</p>
<h2 id="args">Args</h2>
<dl>
<dt>input
: input tensor (AscendArray)</dt>
<dt>dtype
: the converted data type of input.</dt>
<dt><strong><code>context</code></strong></dt>
<dd>input context, optional</dd>
</dl>
<p>stream : input stream, optional
function:
run
: do compute matmul
out
: return output result</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L25-L103" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Cast():
    &#34;&#34;&#34; define a Cast operator object to release dtype convert. support translate types:
        float -&gt; float16, float16 -&gt; float, uint8 -&gt; float16, float16 -&gt; uint8
        uint8 -&gt; float32, float32 -&gt; uint8, float16 -&gt; int32, int32 -&gt; float16  

    Args:
        input  : input tensor (AscendArray)
        dtype  : the converted data type of input.
        context: input context, optional
        stream : input stream, optional

    function:
        run             : do compute matmul
        out             : return output result
    &#34;&#34;&#34;
    def __init__(self, input, dtype=np.dtype(&#39;float16&#39;), context=None, stream=None):
        if not isinstance(input, AscendArray):
            raise TypeError(f&#34;Input tensor expects a AscendArray, but got {type(input)}.&#34;)

        if context and not isinstance(context, int):
            raise TypeError(f&#34;Input context expects an int, but got {type(context)}.&#34;)

        if stream and not isinstance(stream, int):
            raise TypeError(f&#34;Input stream expects an int, but got {type(stream)}.&#34;)

        # assign self value
        self.input = input
        self.context = context
        self.stream = stream if stream else create_stream(context)
        self.created = stream is None

        OpSet()
         # create output array to save result
        self.output = AscendArray(input.shape, dtype=dtype, format=&#39;ND&#39;)
    
        self.tensor_in = TensorDesc(input)
        self.tensor_out = TensorDesc(self.output)

        # do cast operator
        self.run()
        
    def run(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        # do op cast
        ret = acl.op.cast(self.tensor_in.desc,
                          self.tensor_in.buff,
                          self.tensor_out.desc,
                          self.tensor_out.buff,
                          0,
                          self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do op cast, return {ret}.&#34;)

        # do synchronize stream 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in running blas gemm_ex, return {ret}.&#34;)
    
    @property
    def data(self):
        return self.output

    def __del__(self):
        if hasattr(self, &#39;output&#39;):
            del self.output
        if hasattr(self, &#39;tensor_out&#39;):
            del self.tensor_out
        if hasattr(self, &#39;tensor_in&#39;):
            del self.tensor_in

        if self.created:
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, f&#34;destroy stream failed, return {ret}.&#34;</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Cast.data"><code class="name">var <span class="ident">data</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L89-L91" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def data(self):
    return self.output</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Cast.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L66-L87" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    # do op cast
    ret = acl.op.cast(self.tensor_in.desc,
                      self.tensor_in.buff,
                      self.tensor_out.desc,
                      self.tensor_out.buff,
                      0,
                      self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do op cast, return {ret}.&#34;)

    # do synchronize stream 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in running blas gemm_ex, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Color"><code class="flex name class">
<span>class <span class="ident">Color</span></span>
<span>(</span><span>value, names=None, *, module=None, qualname=None, type=None, start=1)</span>
</code></dt>
<dd>
<div class="desc"><p>An enum that defines common colors.</p>
<p>Contains <code>red</code>, <code>green</code>, <code>blue</code>, <code>cyan</code>, <code>yellow</code>, <code>magenta</code>, <code>white</code> and <code>black</code>.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/post_process/color.py#L9-L21" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Color(Enum):
    &#34;&#34;&#34;An enum that defines common colors.

    Contains `red`, `green`, `blue`, `cyan`, `yellow`, `magenta`, `white` and `black`.
    &#34;&#34;&#34;
    red = (0, 0, 255)
    green = (0, 255, 0)
    blue = (255, 0, 0)
    cyan = (255, 255, 0)
    yellow = (0, 255, 255)
    magenta = (255, 0, 255)
    white = (255, 255, 255)
    black = (0, 0, 0)</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>enum.Enum</li>
</ul>
<h3>Class variables</h3>
<dl>
<dt id="ascend.Color.black"><code class="name">var <span class="ident">black</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.blue"><code class="name">var <span class="ident">blue</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.cyan"><code class="name">var <span class="ident">cyan</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.green"><code class="name">var <span class="ident">green</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.magenta"><code class="name">var <span class="ident">magenta</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.red"><code class="name">var <span class="ident">red</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.white"><code class="name">var <span class="ident">white</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
<dt id="ascend.Color.yellow"><code class="name">var <span class="ident">yellow</span></code></dt>
<dd>
<div class="desc"></div>
</dd>
</dl>
</dd>
<dt id="ascend.Context"><code class="flex name class">
<span>class <span class="ident">Context</span></span>
<span>(</span><span>device, acl_json=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a Context class to manage context of device.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>devices</code></strong> :&ensp;<code>set</code></dt>
<dd>save the device configured.</dd>
<dt><strong><code>context_dict</code></strong> :&ensp;<code>dict</code></dt>
<dd>a dict save the map of device id and context.</dd>
<dt><strong><code>device_num</code></strong> :&ensp;<code>int</code></dt>
<dd>The available number of device.</dd>
<dt><strong><code>runmode</code></strong> :&ensp;<code>int</code></dt>
<dd>Running mode of device, same to function <code><a title="ascend.run_mode" href="#ascend.run_mode">run_mode()</a></code>.</dd>
</dl>
<div class="admonition hint">
<p class="admonition-title">Hint</p>
<p>devices = {0,1,2,3} <br>
context_dict = {0:[contex0], <br>
1:[contex1], <br>
2:[contex2], <br>
3:[contex3]} <br></p>
<p>and stream map like: <br>
stream_dict = {contex0:[stream00, stream01], <br>
contex1:[stream10, stream11], <br>
contex2:[stream20, stream21], <br>
contex3:[stream30, stream31]} <br></p>
</div>
<p>Typical usage example:</p>
<pre><code class="language-python"># example 1
device_set = {0, 1}
resource = Context(device_set)
context1 =  resouce.context_dict[0]
context2 =  resouce.context_dict[1]

# example 2
acl_json = &quot;./acl.json&quot;
resource = Context({0, 1}, acl_json)

# example 3
for ctx in Context({0, 1}):
    print(ctx)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L143-L394" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Context():
    &#34;&#34;&#34;Define a Context class to manage context of device.

    Attributes:
        devices (set): save the device configured.
        context_dict (dict): a dict save the map of device id and context.
        device_num (int): The available number of device.
        runmode (int): Running mode of device, same to function `run_mode`.

    .. hint::
        devices = {0,1,2,3} &lt;br&gt;
        context_dict = {0:[contex0], &lt;br&gt;
                        1:[contex1], &lt;br&gt;
                        2:[contex2], &lt;br&gt;
                        3:[contex3]} &lt;br&gt;

        and stream map like: &lt;br&gt;
        stream_dict = {contex0:[stream00, stream01], &lt;br&gt;
                    contex1:[stream10, stream11], &lt;br&gt;
                    contex2:[stream20, stream21], &lt;br&gt;
                    contex3:[stream30, stream31]} &lt;br&gt;

    Typical usage example:
    ```python
    # example 1
    device_set = {0, 1}
    resource = Context(device_set)
    context1 =  resouce.context_dict[0]
    context2 =  resouce.context_dict[1]

    # example 2
    acl_json = &#34;./acl.json&#34;
    resource = Context({0, 1}, acl_json)

    # example 3
    for ctx in Context({0, 1}):
        print(ctx)
    ```
    &#34;&#34;&#34;
    def __init__(self, device, acl_json=None):
        self.class_name = self.__class__.__name__

        if type(self)._first:
            # check input parameters
            self.__check_para(device)

            self.devices = set(device)
            self.context_dict = {}
            self.device_num = 0

            # initial device context resource
            self.__init_resource(acl_json)
            self.__create_context()


    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, &#39;_inst&#39;):   
            cls._inst = super(Context, cls).__new__(cls)
            cls._first = True
        else:
            cls._first = False
            Log(WARNING, &#39;Context is already instantiated&#39;)
        return cls._inst

    def __iter__(self):
        self.iter = iter(self.context_dict.values())
        return self.iter

    def __next__(self):
        return next(self.iter)


    def __check_para(self, devices):
        &#34;&#34;&#34; check input device is in [0, device_num - 1].
        Args:
            devices : input device

        Returns:
            None.
        &#34;&#34;&#34;
        if not isinstance(devices, (list, set, tuple)):
            raise TypeError(f&#34;Input device expects a list/tuple/set, but got {type(devices)}.&#34;)

        if len(devices) == 0:
            raise ValueError(f&#34;Input device is null.&#34;)

        self.device_num, ret = acl.rt.get_device_count()
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Fail to get device in func __check_para, maybe device is \
                        not exist, return {ret}.&#34;)
   
        if self.device_num &lt; len(devices):
            raise ValueError(f&#34;Input param &#39;device&#39; error in func __check_para, \
                        because the elements of device-set exceed {self.device_num}.&#34;) 

        # below we not sure this method is better
        assert sorted(devices)[0] &gt;= 0 and sorted(devices)[-1] &lt; self.device_num, \
            f&#34;Device id {devices} is out of range [0, {self.device_num}).&#34;
   

    def __init_resource(self, acl_json=None):
        &#34;&#34;&#34;initial device resource according to acl_json file.
        Args:
            acl_json : the file path of acl_json.

        Returns:
            None.
        &#34;&#34;&#34;
        if acl_json is None:
            ret = acl.init()  
        elif os.path.exists(acl_json):
            ret = acl.init(acl_json)
        else:
            raise ValueError(f&#34;Fail to open a not existing acl_json file:{acl_json}.&#34;)

        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Fail to init acl in func __init_resource, return {ret}.&#34;)

    def __create_context(self):
        &#34;&#34;&#34; create a context according to input device, and save them to context_dict.
        Args:
            None.

        Returns:
            None.
        &#34;&#34;&#34;
        for device_id in self.devices:
            ret = acl.rt.set_device(device_id)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Set device {device_id} failed in func \
                            __create_context, return {ret}.&#34;)

            context, ret = acl.rt.create_context(device_id)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Create context failed on device {device_id}, return {ret}.&#34;)

            # save the created context to dict
            self.context_dict[device_id] = context

    @classmethod
    def runmode(self, device_id):
        &#34;&#34;&#34;Get the runmode of device

        Args:
            device_id (int): Input device id

        Returns:
            running mode: The runmode of device
        &#34;&#34;&#34;        
        if not isinstance(device_id, int):
            raise TypeError(&#39;device_id expects an int value, &#39;
                                f&#39;but received {type(device_id)}&#39;)

        assert (device_id &gt;= 0) and (device_id &lt; self.device_num), \
                    f&#34;Device id is out of the range [0, {self.device_num}).&#34;

        ret = acl.rt.set_context(self.context_dict[device_id])
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Set device {device_id} failed in func runmode, return {ret}.&#34;)

        run_mode, ret = acl.rt.get_run_mode()
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Get run mode of device {device_id} failed in \
                        func runmode, return {ret}.&#34;)

        return run_mode

    def current_context(self, devnum=None):
        &#34;&#34;&#34;Get the context working on

        Args:
            devnum (int, optional): Input device id. Defaults to None.

        Returns:
            [int]: The context working on
        &#34;&#34;&#34;        
        if devnum in self.context_dict.keys():
            return self.context_dict[devnum]


    def bind_device(self, device_id):
        &#34;&#34;&#34;Bind device resource according to device_id.
            
        .. warning::
            If the context of device_id is not exist, create a context and bind it.

        Args:
            device_id (int): device id.
        &#34;&#34;&#34;
        if not isinstance(device_id, int):
            raise TypeError(f&#34;Input device_id expects an int value, but got {type(device_id)}.&#34;)

        assert (device_id &gt;= 0) and (device_id &lt; self.device_num), \
                    f&#34;Device id is out of the range [0, {self.device_num}).&#34;

        try:
            ret = acl.rt.set_context(self.context_dict[device_id])
            assert ret == ACL_SUCCESS, \
                f&#34;Set context {self.context_dict[device_id]} failed, return {ret}.&#34; 
        except:
            ret = acl.rt.set_device(device_id)
            assert ret == ACL_SUCCESS, \
                f&#34;Failed to set device {device_id} in func bind_device, return {ret}.&#34;

            context, ret = acl.rt.create_context(device_id)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Create context failed on device {device_id}, return {ret}.&#34;)
            self.context_dict[device_id] = context

    def device_available(self):
        &#34;&#34;&#34;Judge the device is available or not

        Returns:
            bool: True for device is available, and False for device number is zero.
        &#34;&#34;&#34;        
        return (self.device_num &gt; 0)

    def stream_add(self):
        &#34;&#34;&#34;Not release yet
        &#34;&#34;&#34;        
        pass

    def context_add(self):
        &#34;&#34;&#34;Not release yet
        &#34;&#34;&#34; 
        pass

    def __release_resource(self):
        &#34;&#34;&#34;release device resource and deinitial.
        Args:
            None.

        Returns:
            None.
        &#34;&#34;&#34;
        for device_id, ctx in self.context_dict.items():
            ret = acl.rt.destroy_context(ctx)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Destroy context {ctx} failed in func \
                        __release_resource, return {ret}.&#34;)
       
            ret = acl.rt.reset_device(device_id)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Reset device {device_id} failed in func \
                        __release_resource, return {ret}.&#34;)
        
        ret = acl.finalize()
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Finalize acl resource failed, return {ret}.&#34;)

    def __del__(self):
        self.__release_resource()</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="ascend.Context.runmode"><code class="name flex">
<span>def <span class="ident">runmode</span></span>(<span>device_id)</span>
</code></dt>
<dd>
<div class="desc"><p>Get the runmode of device</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>device_id</code></strong> :&ensp;<code>int</code></dt>
<dd>Input device id</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>running mode</code></dt>
<dd>The runmode of device</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L282-L308" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@classmethod
def runmode(self, device_id):
    &#34;&#34;&#34;Get the runmode of device

    Args:
        device_id (int): Input device id

    Returns:
        running mode: The runmode of device
    &#34;&#34;&#34;        
    if not isinstance(device_id, int):
        raise TypeError(&#39;device_id expects an int value, &#39;
                            f&#39;but received {type(device_id)}&#39;)

    assert (device_id &gt;= 0) and (device_id &lt; self.device_num), \
                f&#34;Device id is out of the range [0, {self.device_num}).&#34;

    ret = acl.rt.set_context(self.context_dict[device_id])
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Set device {device_id} failed in func runmode, return {ret}.&#34;)

    run_mode, ret = acl.rt.get_run_mode()
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Get run mode of device {device_id} failed in \
                    func runmode, return {ret}.&#34;)

    return run_mode</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Context.bind_device"><code class="name flex">
<span>def <span class="ident">bind_device</span></span>(<span>self, device_id)</span>
</code></dt>
<dd>
<div class="desc"><p>Bind device resource according to device_id.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>If the context of device_id is not exist, create a context and bind it.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>device_id</code></strong> :&ensp;<code>int</code></dt>
<dd>device id.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L323-L350" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def bind_device(self, device_id):
    &#34;&#34;&#34;Bind device resource according to device_id.
        
    .. warning::
        If the context of device_id is not exist, create a context and bind it.

    Args:
        device_id (int): device id.
    &#34;&#34;&#34;
    if not isinstance(device_id, int):
        raise TypeError(f&#34;Input device_id expects an int value, but got {type(device_id)}.&#34;)

    assert (device_id &gt;= 0) and (device_id &lt; self.device_num), \
                f&#34;Device id is out of the range [0, {self.device_num}).&#34;

    try:
        ret = acl.rt.set_context(self.context_dict[device_id])
        assert ret == ACL_SUCCESS, \
            f&#34;Set context {self.context_dict[device_id]} failed, return {ret}.&#34; 
    except:
        ret = acl.rt.set_device(device_id)
        assert ret == ACL_SUCCESS, \
            f&#34;Failed to set device {device_id} in func bind_device, return {ret}.&#34;

        context, ret = acl.rt.create_context(device_id)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Create context failed on device {device_id}, return {ret}.&#34;)
        self.context_dict[device_id] = context</code></pre>
</details>
</dd>
<dt id="ascend.Context.context_add"><code class="name flex">
<span>def <span class="ident">context_add</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Not release yet</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L365-L368" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def context_add(self):
    &#34;&#34;&#34;Not release yet
    &#34;&#34;&#34; 
    pass</code></pre>
</details>
</dd>
<dt id="ascend.Context.current_context"><code class="name flex">
<span>def <span class="ident">current_context</span></span>(<span>self, devnum=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Get the context working on</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>devnum</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Input device id. Defaults to None.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[int]</code></dt>
<dd>The context working on</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L310-L320" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def current_context(self, devnum=None):
    &#34;&#34;&#34;Get the context working on

    Args:
        devnum (int, optional): Input device id. Defaults to None.

    Returns:
        [int]: The context working on
    &#34;&#34;&#34;        
    if devnum in self.context_dict.keys():
        return self.context_dict[devnum]</code></pre>
</details>
</dd>
<dt id="ascend.Context.device_available"><code class="name flex">
<span>def <span class="ident">device_available</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Judge the device is available or not</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool</code></dt>
<dd>True for device is available, and False for device number is zero.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L352-L358" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def device_available(self):
    &#34;&#34;&#34;Judge the device is available or not

    Returns:
        bool: True for device is available, and False for device number is zero.
    &#34;&#34;&#34;        
    return (self.device_num &gt; 0)</code></pre>
</details>
</dd>
<dt id="ascend.Context.stream_add"><code class="name flex">
<span>def <span class="ident">stream_add</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Not release yet</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/context.py#L360-L363" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def stream_add(self):
    &#34;&#34;&#34;Not release yet
    &#34;&#34;&#34;        
    pass</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Image"><code class="flex name class">
<span>class <span class="ident">Image</span></span>
<span>(</span><span>context=None, stream=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Define an Image class to process image.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code></dt>
<dd>The context resource working on</dd>
<dt><strong><code>stream</code></strong> :&ensp;<code>int</code></dt>
<dd>The stream resource working on</dd>
</dl>
<div class="admonition hint">
<p class="admonition-title">Hint</p>
<ul>
<li>imdecode
: reads an image from the specified numpy ndarray and decode to yuv image</li>
<li>imresize
: resizes the image img down to or up to the specified size</li>
<li>imrescale : Resize image while keeping the aspect ratio.</li>
<li>imflip
: Flip an image horizontally or vertically</li>
<li>imrotate
: Rotate an image</li>
<li>imcrop
: Crop image patches</li>
</ul>
</div></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L278-L1273" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Image():
    &#34;&#34;&#34;Define an Image class to process image.

    Attributes:
       context (int): The context resource working on
       stream (int): The stream resource working on


    .. hint:: 
       - imdecode  : reads an image from the specified numpy ndarray and decode to yuv image
       - imresize  : resizes the image img down to or up to the specified size
       - imrescale : Resize image while keeping the aspect ratio.
       - imflip    : Flip an image horizontally or vertically
       - imrotate  : Rotate an image
       - imcrop    : Crop image patches

    &#34;&#34;&#34;
    def __init__(self, context=None, stream=None):
        self.class_name = self.__class__.__name__
        self.context = context
 
        # create a stream according to context
        self.stream = create_stream(context, stream)

        # create dvpp image processing channel
        self._channel_desc = acl.media.dvpp_create_channel_desc()
        ret = acl.media.dvpp_create_channel(self._channel_desc)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;create channel failed, return {ret}.&#34;)

    def imdecode(self, array, format=PIXEL_FORMAT_YUV_SEMIPLANAR_420, return_shape=False):
        &#34;&#34;&#34; imdecode(array, format) -&gt; retval
        
        .. note::
            The function imdecode reads an image from the specified numpy ndarray and decode to yuv image.
            See www.hiascend.com for the list of supported format.

        Args:
            array (ndarray): Input numpy ndarray.
            format (int, optional): The supported decode image format. Defaults to PIXEL_FORMAT_YUV_SEMIPLANAR_420.
            return_shape (bool, optional): Return original shape(h, w, c) of image.

        Returns:
            AscendArray : The decoded image(AscendArray obj)

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        data = np.fromfile(&#39;./image.jpg&#39;, dtype=np.uint8)
        image = Img.imdecode(data)
        ```
        &#34;&#34;&#34;
        if not isinstance(array, np.ndarray):
            raise TypeError(f&#34;Input array expects an np.ndarray object, but got {type(array)}.&#34;)

        img_ptr = acl.util.numpy_to_ptr(array)

        w, h, c, ret = acl.media.dvpp_jpeg_get_image_info(img_ptr, array.nbytes)
        if ret == ACL_SUCCESS:
            decoder = &#39;jpg&#39;
        else:
            w, h, c, ret = acl.media.dvpp_png_get_image_info(img_ptr, array.nbytes)
            assert ret ==ACL_SUCCESS, f&#34;Get input image&#39;s info failed, return {ret}.&#34;
            decoder = &#39;png&#39;

        constrain_ = 8192 if decoder == &#39;jpg&#39; else 4096
        if w &lt; 32 or w &gt; constrain_:
            raise ValueError(f&#34;Input image&#39;s width out of range [32, {constrain_}].&#34;)

        if h &lt; 32 or h &gt; constrain_:
            raise ValueError(f&#34;Input image&#39;s height out of range [32, {constrain_}].&#34;)

        if decoder == &#39;jpg&#39; and format not in [
            PIXEL_FORMAT_YUV_SEMIPLANAR_420,
            PIXEL_FORMAT_YVU_SEMIPLANAR_420,
            PIXEL_FORMAT_YVU_SEMIPLANAR_422,
            PIXEL_FORMAT_YVU_SEMIPLANAR_444
            ]:
            raise ValueError(f&#34;Input decode {format} is invalid, this format is unsupport.&#34;)

        if decoder ==&#39;png&#39; and format not in [
            PIXEL_FORMAT_RGB_888,
            PIXEL_FORMAT_BGR_888,
            PIXEL_FORMAT_ARGB_8888,
            PIXEL_FORMAT_ABGR_8888,
            PIXEL_FORMAT_RGBA_8888,
            PIXEL_FORMAT_BGRA_8888
            ]:
            raise ValueError(f&#34;Input decode {format} is invalid, this format is unsupport.&#34;)

        if self._channel_desc is None:
            raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

        # clone input image to device
        data = AscendArray.clone(array, context=self.context, flag=&#34;DVPP&#34;)

        image = _create_align_img(w, h, format=format, func=&#39;jpegd&#39; if decoder == &#39;jpg&#39; else &#39;pngd&#39;)

        # create output image desc and bind it with a output AscendArray object
        pic_inst = PicDesc(image, (w, h))

        # do jpeg decode
        if decoder == &#39;jpg&#39;:
            ret = acl.media.dvpp_jpeg_decode_async(self._channel_desc,
                                                data.ascend_data,
                                                data.nbytes,
                                                pic_inst.desc,
                                                self.stream)
            assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_jpeg_decode_async, return {ret}.&#34;
        else:
            ret = acl.media.dvpp_png_decode_async(self._channel_desc,
                                                data.ascend_data,
                                                data.nbytes,
                                                pic_inst.desc,
                                                self.stream)
            assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_png_decode_async, return {ret}.&#34;
        
        # finish jpeg image decode
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to decode jpeg image in synchronize_stream, return {ret}.&#34;)

        # release the unused resource in future
        del (data, pic_inst)
        Log(INFO, &#39;imdecode success.&#39;)
        if return_shape:
            return image, (h, w, c)
        else:
            return image


    def imencode(self, ext, img, params=None):
        &#34;&#34;&#34; Encodes an image into a memory buffer.
         
        .. note::
            The function imencode compresses the image and stores it in the memory buffer 
            that is resized to fit the result. See www.hiascend.com for the list of 
            supported format and flags description.
         
        Args:
            ext (str): File extension that defines the output format.
            img (AscendArray): Image to be written
            params (str, optional): Format-specific parameters, not use.

        Returns:
            AscendArray : Output buffer resized to fit the compressed image.
        
        Typical usage example:
        ```python
        img_encode = img.imencode(&#39;.jpg&#39;, yuv_img)
        str_encode = np.array(img_encode).tostring()
        ```
        &#34;&#34;&#34;
        if ext not in IMG_EXT_ENC:
            raise TypeError(f&#34;Input ext expects {IMG_EXT_ENC}, but got {ext}.&#34;)

        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

        if img.format not in [
            PIXEL_FORMAT_YUV_SEMIPLANAR_420,
            PIXEL_FORMAT_YVU_SEMIPLANAR_420,
            PIXEL_FORMAT_YUYV_PACKED_422, 
            PIXEL_FORMAT_UYVY_PACKED_422, 
            PIXEL_FORMAT_YVYU_PACKED_422,
            PIXEL_FORMAT_VYUY_PACKED_422
            ]:
            raise ValueError(f&#34;Encode img&#39;s format {img.format} is invalid, this format not support.&#34;)

        if self._channel_desc is None:
            raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

        src_img, shape = _align_img(img, func=&#39;encode&#39;)

        # create input image desc and bind it with a input AscendArray object
        src_inst = PicDesc(src_img, shape)

        # create a jpeg image encode configurate
        config = acl.media.dvpp_create_jpege_config()
        ret = acl.media.dvpp_set_jpege_config_level(config, 100)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Set jpege config level failed, return {ret}.&#34;)

        # predict out buffer size according to image desc
        buff_size, ret = acl.media.dvpp_jpeg_predict_enc_size(src_inst.desc, config)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;jpeg predict encode size failed, return {ret}.&#34;)

        # config out buffer of encode
        out_size = np.array([buff_size], dtype=np.int32)
        size_ptr = acl.util.numpy_to_ptr(out_size)
        enc_jpg = AscendArray((buff_size,), np.dtype(&#39;uint8&#39;), format=img.format, flag=&#39;DVPP&#39;)
        
        # do jpeg decode
        ret = acl.media.dvpp_jpeg_encode_async(self._channel_desc,
                                               src_inst.desc,
                                               enc_jpg.ascend_data,
                                               size_ptr,
                                               config,
                                               self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_jpeg_encode_async, return {ret}.&#34;)
        
        # finish jpeg image decode
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to encode jpeg image in synchronize_stream, return {ret}.&#34;)

        # trans AscendArray data to numpy array
        jpeg_img = enc_jpg.to_np

        # release the unused resource in future
        del (src_inst, src_img, enc_jpg)
        Log(INFO, &#39;imdecode success.&#39;)

        ret = acl.media.dvpp_destroy_jpege_config(config)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;destroy jpege config failed, return {ret}.&#34;)
        return jpeg_img


    def imresize(self, img, dsize, interpolation=&#39;huawei&#39;):
        &#34;&#34;&#34;imresize(array, img, dsize, interpolation=&#39;huawei&#39;) -&gt; retval

        To shrink an image, it will generally look best with #INTER_AREA interpolation

        Args:
            img (AscendArray): Input image
            dsize (tuple): The output image size (tuple(w, h));
            interpolation (str, optional): The interpolation method, its default method is researched 
                by ourself.. Defaults to &#39;huawei&#39;.

        Returns:
            AscendArray: The resized image

        .. note::
            The function resize resizes the image img down to or up to the specified size. Note that the
            initial dst type or size are not taken into account. Instead, the size and type are derived from
            the img, dsize. 

        you may call the function as follows:
        ```python
        # explicitly specify dsize (tuple[int]): Target size (w, h).
        imresize(img, dsize, interpolation)
        ```
        If you want to decimate the image by factor of 2 in each direction, you can call the function this way:
        ```python
        # specify the element w and h of the destination image size.
        imresize(img, (w//2, h//2), interpolation)
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

        # valid format is in range [PIXEL_FORMAT_YUV_400 -&gt; PIXEL_FORMAT_BGRA_8888]
        if img.format &lt; 0 or img.format &gt; 17:
            raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
                [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

        # get the truth h and w of image.
        if img.format in yuv420:
            h, w = (img.shape[0] * 2 // 3, img.shape[1])
        else:
            h, w = img.shape[:2]

        if dsize and not isinstance(dsize, tuple):
            raise TypeError(f&#34;Input dsize expects a tuple object, but got {type(dsize)}.&#34;)

        if dsize and (dsize[0] &gt; 16 * w or dsize[0] &lt; int(1/32 * w)):
            raise ValueError(f&#34;Input dsize[0] out of resize ratio [1/32, 16]&#34;)

        if dsize and (dsize[1] &gt; 16 * h or dsize[1] &lt; int(1/32 * h)):
            raise ValueError(f&#34;Input dsize[1] out of resize ratio [1/32, 16]&#34;)

        if interpolation not in interp_codes.keys():
            raise ValueError(f&#34;Input decode flag {interpolation} is unsupport.&#34;)

        if self._channel_desc is None:
            raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

        # do image aligned and create aligned image to save resized image
        src_img, shape = _align_img(img, func=&#39;resize&#39;)
        dst_img = _create_align_img(dsize[0], dsize[1], format=img.format, func=&#39;resize&#39;)

        # create output image desc and bind it with a output AscendArray object
        # warning: The dst_inst must defined as dst_inst = PicDesc(dst_img), not to be
        #          define as dst_inst = PicDesc(dst_img, dsize), otherwise, the dst image&#39;s
        #          last lines will filled with random colors(value).
        src_inst = PicDesc(src_img, shape)
        dst_inst = PicDesc(dst_img)

        # create resize config
        resize_conf = acl.media.dvpp_create_resize_config()

        # set resize interpolation
        ret = acl.media.dvpp_set_resize_config_interpolation(resize_conf, interp_codes[interpolation])
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set resize_config_interpolation, return {ret}.&#34;)

        # do image resize
        ret = acl.media.dvpp_vpc_resize_async(self._channel_desc,
                                              src_inst.desc,
                                              dst_inst.desc,
                                              resize_conf,
                                              self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_vpc_resize_async, return {ret}.&#34;)

        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to resize image in synchronize_stream, return {ret}.&#34;)

        ret = acl.media.dvpp_destroy_resize_config(resize_conf)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;do dvpp_destroy_resize_config failed, return {ret}.&#34;)

        del (img, src_img, src_inst, dst_inst)
        Log(INFO, &#39;resize image success&#39;)

        return dst_img


    def imrescale(self, img, scale, interpolation=&#39;huawei&#39;, return_shape=False):
        &#34;&#34;&#34;Resize image while keeping the aspect ratio.

        Args:
            img (AsecendArray): The input image.
            scale (float, tuple[int]): The scaling factor or maximum size. If it is a float 
                number, then the image will be rescaled by this factor, else if it is a tuple 
                of 2 integers, then the image will be rescaled as large as possible within 
                the scale.
            interpolation (str, optional): Same as :func:`imresize`.
            return_shape (bool, optional): Return scale shape not aligned.

        Returns:
            AsecendArray : The rescaled image.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        yuv_rescale1 = Img.imrescale(yuv, 0.3)
        yuv_rescale2 = Img.imrescale(yuv, (320, 540))
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

        # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
        if img.format &lt; 0 or img.format &gt; 17:
            raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
                [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

        # get the truth h and w of image.
        if img.format in yuv420:
            h, w = (img.shape[0] * 2 // 3, img.shape[1])
        else:
            h, w = img.shape[:2]

        if isinstance(scale, (float, int)):
            if scale &lt;= 0:
                raise ValueError(f&#39;Invalid scale {scale}, must be positive.&#39;)  
            scale_factor = scale
        elif isinstance(scale, tuple):
            max_long_edge = max(scale)
            max_short_edge = min(scale)

            # find the maximum rescale ratio, and the resized shape should be valid.
            scale_factor = min(max_long_edge/max(h, w), max_short_edge/min(h, w))
        else:
            raise TypeError(
                f&#39;Scale must be a number or tuple of int, but got {type(scale)}&#39;)

        # caculate new rescaled size according to scale_factor 
        new_size = _scale_size((w, h), scale_factor)

        # do resize
        rescaled_img = self.imresize(img, new_size, interpolation=interpolation)

        if return_shape:
            return rescaled_img, new_size
        else:
            return rescaled_img

    def imflip(self, img, direction=&#39;horizontal&#39;):
        &#34;&#34;&#34;Flip an image horizontally or vertically.

        Args:
            img (AscendArray): Image to be flipped.
            direction (str): The flip direction, either &#34;horizontal&#34; or &#34;vertical&#34; or &#34;diagonal&#34;.

        Returns:
            AscendArray: The flipped image.
        
        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        im_flip = Img.imflip(img, direction=&#39;horizontal&#39;)
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

        # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
        if img.format &lt; 0 or img.format &gt; 17:
            raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
                [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

        assert direction in [&#39;horizontal&#39;, &#39;vertical&#39;, &#39;diagonal&#39;]

        arr = img.to_np

        if direction == &#39;horizontal&#39;:
            return AscendArray.clone(np.flip(arr, axis=1))
        elif direction == &#39;vertical&#39;:
            return AscendArray.clone(np.flip(arr, axis=0))
        else:
            return AscendArray.clone(np.flip(arr, axis=(0, 1)))


    def imrotate(self, 
                img,
                angle,
                center=None,
                scale=1.0,
                border_value=0,
                interpolation=&#39;bilinear&#39;,
                auto_bound=False):
        &#34;&#34;&#34;Rotate an image.

        Args:
            img (AscendArray): Image to be rotated.
            angle (float): Rotation angle in degrees, positive values mean clockwise rotation.
            center (tuple[float], optional): Center point (w, h) of the rotation in the source 
                image. If not specified, the center of the image will be used.
            scale (float, optional): Isotropic scale factor.
            border_value (int, optional): Border value.
            interpolation (str, optional): Same as function: `resize`.
            auto_bound (bool, optional): Whether to adjust the image size to cover the whole
                rotated image.

        Returns:
            AscendArray: The rotated image.
        &#34;&#34;&#34;
        try:
            import cv2
            cv2_interp_codes = {
                &#39;nearest&#39;: cv2.INTER_NEAREST,
                &#39;bilinear&#39;: cv2.INTER_LINEAR,
                &#39;bicubic&#39;: cv2.INTER_CUBIC,
                &#39;area&#39;: cv2.INTER_AREA,
                &#39;lanczos&#39;: cv2.INTER_LANCZOS4
            }
        except ImportError:
            Log(ERROR, &#39;import cv2 error while using imrotate, you should install opencv first.&#39;)
            return

        if center is not None and auto_bound:
            raise ValueError(&#39;`auto_bound` conflicts with `center`&#39;)
        h, w = img.shape[:2]
        if center is None:
            center = ((w - 1) * 0.5, (h - 1) * 0.5)
        assert isinstance(center, tuple)

        matrix = cv2.getRotationMatrix2D(center, -angle, scale)
        if auto_bound:
            cos = np.abs(matrix[0, 0])
            sin = np.abs(matrix[0, 1])
            new_w = h * sin + w * cos
            new_h = h * cos + w * sin
            matrix[0, 2] += (new_w - w) * 0.5
            matrix[1, 2] += (new_h - h) * 0.5
            w = int(np.round(new_w))
            h = int(np.round(new_h))
        rotated = cv2.warpAffine(
            img.to_np,
            matrix, (w, h),
            flags=cv2_interp_codes[interpolation],
            borderValue=border_value)
        return AscendArray.clone(rotated)
        

    def imcrop(self, img, bboxes, scale=1.0):
        &#34;&#34;&#34;Crop image patches, and resize bboxes.

        Args:
            img (AscendArray): Image to be cropped.
            bboxes (ndarray): Shape (k, 4) or (4,), location of cropped bboxes.
            scale (float, optional): Scale ratio of bboxes, the default value 1.0 means no padding.

        Returns:
            list[AscendArray] or AscendArray: The cropped image patches.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
        yuv_croped = Img.imcrop(img, bboxes)
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray, but we got a {type(img)}.&#34;)

        # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
        if img.format &lt; 0 or img.format &gt; 17:
            raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
                [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

        if not isinstance(bboxes, np.ndarray):
            raise TypeError(f&#34;Input bbox expects an np.ndarray, but we got a {type(bboxes)}.&#34;)

        if self._channel_desc is None:
            raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

        # step 1: caculate the cliped bbox shape
        _bboxes = bboxes[None, ...] if bboxes.ndim == 1 else bboxes
        scaled_bboxes = bbox_scaling(_bboxes, scale).astype(np.int32)
        clipped_bbox = _align_roi(scaled_bboxes, img)
        
        # align original image
        src_img, shape = _align_img(img, func=&#39;crop&#39;)

        # step 2: input desc assembling, only process one image.
        image_inst = PicDesc([src_img], shape)
        roi_n_list = [clipped_bbox.shape[0]]

        # step 3: clip bboxes of image
        bboxes, roi_list = [], []
        for i in range(clipped_bbox.shape[0]):
            x1, y1, x2, y2 = clipped_bbox[i, :].tolist()
            
            # create a bbox(a AscendArray object) and bind with dvpp memory
            dst_image = _create_align_img(x2 - x1, y2 - y1, format=img.format, func=&#39;crop&#39;)
            bboxes.append(dst_image)

            # create roi description
            roi_conf = acl.media.dvpp_create_roi_config(x1, x2, y1, y2)
            roi_list.append(roi_conf)

        # create output image desc and bind it with a output AscendArray object
        bboxes_inst = PicDesc(bboxes)

        # step 4: crop processing
        _, ret = acl.media.dvpp_vpc_batch_crop_async(
                                            self._channel_desc,
                                            image_inst.desc, 
                                            roi_n_list,
                                            bboxes_inst.desc,
                                            roi_list,
                                            self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_vpc_crop_async, return {ret}.&#34;)

        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to crop image in synchronize_stream, return {ret}.&#34;)
        
        for roi in roi_list:
            ret = acl.media.dvpp_destroy_roi_config(roi)
            assert ret == ACL_SUCCESS, \
                ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

        del image_inst, bboxes_inst
        Log(INFO, &#39;vpc crop process success&#39;)

        if not np.isclose(scale, 1.0, rtol=1e-2, atol=1e-03):
            res_img = []
            for bbox in bboxes:
                res_img.append(self.imrescale(bbox, scale))
            return res_img

        return bboxes

    def bbox_resize(self, img, bboxes, sizes, inner_resize=True):
        &#34;&#34;&#34;Clip the bboxes image and resize to specified size.

        2 steps:  clip the bboxes image -&gt; resize croped image.

        Args:
            img (AscendArray): Image to be cliped.
            bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes.
            sizes (int): Shape (k, 2) or (2, ), scale sizes of bboxes.
            inner_resize (bool, optional): Use dvpp auto resize function to resize croped boxes

        Returns:
            list[AscendArray] or AscendArray: The cropped and resized image patches.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
        sizes = np.array([[300, 300], [400, 400]])
        yuv_croped = Img.bbox_resize(img, bboxes, sizes)
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray, but we got {type(img)}.&#34;)

        # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
        if img.format &lt; 0 or img.format &gt; 17:
            raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
                [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

        if not isinstance(bboxes, np.ndarray):
            raise TypeError(f&#34;Input bboxes expects an np.ndarray, but given {type(bboxes)}.&#34;)

        if not isinstance(sizes, np.ndarray):
            raise TypeError(f&#34;Input sizes expects an np.ndarray, but given {type(sizes)}.&#34;)

        if self._channel_desc is None:
            raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

        assert sizes.shape[-1] == 2, f&#34;Input sizes dim 2 must be 2.&#34;
        if sizes.ndim == 2 and sizes.shape[0] != bboxes.shape[0]:
            raise ValueError(f&#34;Input sizes&#39;s shape expects same to bboxes.&#34;)

        # step 1: caculate the cliped bbox shape
        _bboxes = bboxes[None, ...] if bboxes.ndim == 1 else bboxes
        scaled_bboxes = bbox_scaling(_bboxes, 1.0).astype(np.int32)
        clipped_bbox = _align_roi(scaled_bboxes, img)

        # align original image 
        src_img, shape = _align_img(img, func=&#39;crop&#39;)

        # step 2: input desc assembile, only process one image.
        image_inst = PicDesc([src_img], shape)
        roi_n_list = [clipped_bbox.shape[0]]

        # step 3: clip bboxes of image
        bboxes, roi_list = [], []
        _sizes = sizes[None, ...].tolist() if sizes.ndim == 1 else sizes.tolist()
        for i in range(clipped_bbox.shape[0]):
            x1, y1, x2, y2 = clipped_bbox[i, :].tolist()

            # align w and h, and calc memory size of output box image
            if inner_resize:
                dst_image = _create_align_img(_sizes[i][0], _sizes[i][1], format=img.format, func=&#39;crop&#39;)
            else:
                dst_image = _create_align_img(x2 - x1, y2 - y1, format=img.format, func=&#39;crop&#39;)
            bboxes.append(dst_image)

            # create roi description
            roi_conf = acl.media.dvpp_create_roi_config(x1, x2, y1, y2)
            roi_list.append(roi_conf)

        # create output image desc and bind it with a output AscendArray object
        bboxes_inst = PicDesc(bboxes)

        # step 4: crop processing
        _, ret = acl.media.dvpp_vpc_batch_crop_async(
                                            self._channel_desc,
                                            image_inst.desc, 
                                            roi_n_list,
                                            bboxes_inst.desc,
                                            roi_list,
                                            self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_vpc_crop_async, return {ret}.&#34;)

        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to crop image in synchronize_stream, return {ret}.&#34;)
        
        for roi in roi_list:
            ret = acl.media.dvpp_destroy_roi_config(roi)
            assert ret == ACL_SUCCESS, \
                ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

        del (image_inst, bboxes_inst)
        Log(INFO, &#39;vpc crop process success&#39;)

        if not inner_resize:
            res_img = []
            for bbox in bboxes:
                res_img.append(self.imresize(bbox, _sizes[i]))
            return res_img

        return bboxes


    def imcrop_paste(self, src_img, dst_img, crop_bbox, paste_bbox):
        &#34;&#34;&#34;Crop a bbox from src image and paste the cropped bbox to dst image

        Args:
            src_img (AscendArray): Input src image(AscendArray) to be croped.
            dst_img (AscendArray): Input dst image(AscendArray) to be pasted.
            crop_bbox (np.ndarray): Shape (4, ) or (n, 4), location of cropped bboxe, data arrangement,
                np.array([startx, starty, endx, endy], dtype=int).
            paste_bbox (np.ndarray): Shape (4, ) or (n, 4), location of pasted bboxe, data arrangement
                same to crop_bbox.

        Returns:
            AscendArray: Dest image after cropping and pasting.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        crop_bbox = np.array([40, 30, 140, 230], dtype=&#39;int32&#39;)
        paste_bbox = np.array([70, 80, 170, 280], dtype=&#39;int32&#39;)
        Img.imcrop_paste(yuv_src, yuv_dst, crop_bbox, paste_bbox)
        ```
        &#34;&#34;&#34;

        if not isinstance(src_img, AscendArray):
            raise TypeError(f&#34;Input src_img expects an AscendArray, but we got a {type(src_img)}.&#34;)

        if not isinstance(dst_img, AscendArray):
            raise TypeError(f&#34;Input dst_img expects an AscendArray, but we got a {type(dst_img)}.&#34;)

        if not isinstance(crop_bbox, np.ndarray):
            raise TypeError(f&#34;Input bbox expects an np.ndarray, but we got a {type(crop_bbox)}.&#34;)

        if not isinstance(paste_bbox, np.ndarray):
            raise TypeError(f&#34;Input bbox expects an np.ndarray, but we got a {type(crop_bbox)}.&#34;)

        if crop_bbox.shape[-1] != 4 or paste_bbox.shape[-1] != 4:
            raise ValueError(f&#34;Input crop_bbox or paste_bbox column dim should be 4.&#34;)

        if crop_bbox.shape[0] != paste_bbox.shape[0]:
            raise ValueError(f&#34;Input crop_bbox and paste_bbox should have same number bbox.&#34;)

        # step 1: clip input bbox to fit image, make startx and starty to even and endx and endy to odd
        cbbox = _align_roi(crop_bbox, src_img).tolist()
        pbbox = _align_roi(paste_bbox, dst_img, is_paste=True).tolist()

        # step 2: align original image
        crop_img, shape_c = _align_img(src_img, func=&#39;crop&#39;)
        paste_img, shape_p = _align_img(dst_img, func=&#39;crop&#39;)

        # step 3: create output image desc and bind it with a output AscendArray object
        src_desc = PicDesc([crop_img], shape_c)
        dst_desc = PicDesc([paste_img] * len(pbbox), shape_p)

        # step 4: startx of paste box aligned to 16 and append crop/paste roi to list
        crop_conf_list, past_conf_list = [], []
        for i in range(len(pbbox)):
            crop_conf = acl.media.dvpp_create_roi_config(
                cbbox[i][0], cbbox[i][2], cbbox[i][1], cbbox[i][3])
            past_conf = acl.media.dvpp_create_roi_config(
                pbbox[i][0], pbbox[i][2], pbbox[i][1], pbbox[i][3])
            crop_conf_list.append(crop_conf)
            past_conf_list.append(past_conf)

        # step 5: do crop and paste
        _, ret = acl.media.dvpp_vpc_batch_crop_and_paste_async(self._channel_desc,
                                                            src_desc.desc,
                                                            [len(pbbox)], 
                                                            dst_desc.desc,
                                                            crop_conf_list, 
                                                            past_conf_list,
                                                            self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_vpc_batch_crop_and_paste_async, return {ret}.&#34;)

        # step 6: synchronize stream and finish crop and paste 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to crop and paste image in synchronize_stream, return {ret}.&#34;)

        for conf in crop_conf_list:
            ret = acl.media.dvpp_destroy_roi_config(conf)
            assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;

        for conf in past_conf_list:
            ret = acl.media.dvpp_destroy_roi_config(conf)
            assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;

        del (crop_img, src_desc, dst_desc)
        Log(INFO, &#39;crop and paste process success&#39;)
        return paste_img

    def impad(self, img, shape=None, padding=None, pad_val=0, padding_mode=&#39;constant&#39;):
        &#34;&#34;&#34;Pad the given image to a certain shape or pad on all sides with
            specified padding mode and padding value.

        Args:
            img (AscendArray): Image to be padded.
            shape (tuple[int]): Expected padding shape (h, w). Default: None.
            padding (int or tuple[int]): Padding on each border. If a single int is provided this 
                is used to pad all borders. If tuple of length 2 is provided this is the padding 
                on left/right and top/bottom respectively. If a tuple of length 4 is provided 
                this is the padding for the [left, top, right and bottom] borders respectively.
                Default: None. Note that `shape` and `padding` can not be both set.
            pad_val (Number): Values to be filled in padding areas when padding_mode is 
                &#39;constant&#39;. Default: 0.
            padding_mode (str): Type of padding. Only support: constant. Default: constant.

                - constant: pads with a constant value, this value is specified with pad_val.

        Returns:
            AscendArray : The padded image.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        yuv_pad = Img.impad(img, padding=(20, 50, 100, 200), pad_val=128)
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray, but we got a {type(img)}.&#34;)

        if shape and not isinstance(shape, tuple):
            raise TypeError(f&#34;Input shape expects an tuple, but we got a {type(shape)}.&#34;)

        if padding and not isinstance(padding, (int, tuple)):
            raise TypeError(f&#34;Input padding expects an int or tuple, but we got a {type(padding)}.&#34;)

        if padding_mode not in [&#39;constant&#39;]:
            raise TypeError(f&#34;Input padding_mode expects in [&#39;constant&#39;], but we got {padding_mode}.&#34;)

        assert (shape is not None) ^ (padding is not None), \
                f&#34;Input `shape` and `padding` can not be both set.&#34;

        # get the truth h and w of image.
        if img.format in yuv420:
            h, w = (img.shape[0] * 2 // 3, img.shape[1])
        else:
            h, w = img.shape[:2]

        if shape is not None:
            padding = (0, 0, shape[1] - w, shape[0] - h)

        if isinstance(padding, tuple) and len(padding) in [2, 4]:
            if len(padding) == 2:
                padding = (padding[0], padding[1], padding[0], padding[1])
        elif isinstance(padding, numbers.Number):
            padding = (padding, padding, padding, padding)
        else:
            raise ValueError(&#39;Padding must be a int or a 2, or 4 element tuple.&#39;
                            f&#39;But received {padding}&#39;)

        # align original image shape and create a output to save padding result.
        src_img, src_shape = _align_img(img)
        dst_w, dst_h = padding[0] + w + padding[2], padding[1] + h + padding[3]
        dst_img = _create_align_img(dst_w, dst_h, format=img.format)

        # set the padding result&#39;s memory with pad_val
        Memory.reset(dst_img.ascend_data, dst_img.nbytes, pad_val)

        # create output image desc and bind it with a output AscendArray object
        src_desc = PicDesc(src_img, src_shape)
        dst_desc = PicDesc(dst_img, (dst_h, dst_w))

        # paste area startx, starty, endx, endy, and align startx with 16
        startx = aligned(padding[0], aligned=&#39;w&#39;)
        starty = padding[1] &gt;&gt; 1 &lt;&lt; 1
        endx = ((startx + w) &gt;&gt; 1 &lt;&lt; 1) - 1
        endy = ((padding[1] + h) &gt;&gt; 1 &lt;&lt; 1) - 1

        # create roi description
        roi_conf = acl.media.dvpp_create_roi_config(0, (w &gt;&gt; 1 &lt;&lt; 1) - 1, 0, (h &gt;&gt; 1 &lt;&lt; 1) - 1)
        pst_conf = acl.media.dvpp_create_roi_config(startx, endx, starty, endy)

        ret = acl.media.dvpp_vpc_crop_and_paste_async(self._channel_desc,
                                                      src_desc.desc,
                                                      dst_desc.desc,
                                                      roi_conf,
                                                      pst_conf,
                                                      self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_vpc_crop_and_paste_async, return {ret}.&#34;)

        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to crop and paste image in synchronize_stream, return {ret}.&#34;)

        ret = acl.media.dvpp_destroy_roi_config(roi_conf)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

        ret = acl.media.dvpp_destroy_roi_config(pst_conf)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

        del (src_img, src_desc, dst_desc)
        Log(INFO, &#39;image padding process success&#39;)
        return dst_img

    def imread(self, img_or_path, flag=&#39;color&#39;, channel_order=&#39;bgr&#39;, backend=&#39;ascend&#39;, keep_shape=False):
        &#34;&#34;&#34;Read an image.

        Args:
            img_or_path (ndarray or str or Path): Either a numpy array or str or pathlib.Path. If 
                it is a numpy array (loaded image), then it will be returned as is.
            flag (str): Flags specifying the color type of a loaded image, candidates are `color`, 
                `grayscale` and `unchanged`. It only work for `cv2` and `pillow`.
            channel_order (str): Order of channel, candidates are `bgr` and `rgb`, not work for ascend.
            backend (str): The image decoding backend type. Options are `cv2`, `pillow`, `ascend`. 
                Default: `ascend`.

        Returns:
            AscendArray: Loaded image array.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        yuv = Img.imread(&#39;./image.jpg&#39;)
        ```
        &#34;&#34;&#34;
        if backend not in [&#39;cv2&#39;, &#39;pillow&#39;, &#39;ascend&#39;]:
            raise ValueError(f&#39;backend: {backend} is not supported. Supported &#34;backends are &#39;
                            &#34;&#39;cv2&#39;, &#39;pillow&#39;, &#39;ascend&#39;.&#34;)

        if backend == &#39;cv2&#39;:
            try:
                import cv2
                imread_flags = {
                    &#39;color&#39;: cv2.IMREAD_COLOR,
                    &#39;grayscale&#39;: cv2.IMREAD_GRAYSCALE,
                    &#39;unchanged&#39;: cv2.IMREAD_UNCHANGED
                }
            except ImportError:
                Log(ERROR, &#34;import cv2 error while using imread with backend &#39;cv2&#39;.&#34;)
                return

        if isinstance(img_or_path, Path):
            img_or_path = str(img_or_path)

        if isinstance(img_or_path, np.ndarray): 
            if keep_shape:           
                decode_img, ori_shape = self.imdecode(img_or_path, return_shape=True)
                return self.imcrop(decode_img, np.array([0, 0, ori_shape[1] - 1, ori_shape[0] - 1]))[0]
            else:
                return self.imdecode(img_or_path)
        elif is_str(img_or_path):
            check_file_exist(img_or_path, f&#39;img file does not exist: {img_or_path}&#39;)
            if backend == &#39;pillow&#39;:
                img = Image.open(img_or_path)
                img = _pillow2array(img, flag, channel_order)
                return AscendArray.clone(img)
            elif backend == &#39;cv2&#39;:
                flag = imread_flags[flag] if is_str(flag) else flag
                img = cv2.imread(img_or_path, flag)
                if flag == cv2.IMREAD_COLOR and channel_order == &#39;rgb&#39;:
                    cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
                return AscendArray.clone(img)
            else:
                array = np.fromfile(img_or_path, dtype=np.uint8)
                if keep_shape:
                    decode_img, ori_shape = self.imdecode(array, return_shape=True)
                    return self.imcrop(decode_img, np.array([0, 0, ori_shape[1] - 1, ori_shape[0] - 1]))[0]
                else:
                    return self.imdecode(array)
        else:
            raise TypeError(&#39;&#34;img&#34; must be a numpy array or a str or a pathlib.Path object&#39;)


    def imwrite(self, img, file_path, params=None, auto_mkdir=True):
        &#34;&#34;&#34;Write image to file.

        Args:
            img (AscendArray): Image array to be written.
            file_path (str): Image file path.
            params (None, str or list): If params==&#39;pillow&#39;, save image with PIL. if params is list, 
                this same as opencv&#39;s func: `imwrite` interface, only work for opencv.
            auto_mkdir (bool): If the parent folder of `file_path` does not exist,
                whether to create it automatically.

        Returns:
            bool: Successful or not.

        Typical usage example:
        ```python
        Img = ascend.Image(ctx)
        Img.imwrite(yuv_org, &#39;./saved_img.jpg&#39;)  
        ```
        &#34;&#34;&#34;
        if not isinstance(img, AscendArray):
            raise TypeError(f&#34;Input img expects an AscendArray, but got {type(img)}.&#34;)
        
        if auto_mkdir:
            dir_name = osp.abspath(osp.dirname(file_path))
            mkdir_or_exist(dir_name)
        
        if params is None:
            ext = &#39;.png&#39; if file_path.endswith(&#39;.png&#39;) or file_path.endswith(&#39;.PNG&#39;)  else &#39;.jpg&#39;
            file = self.imencode(ext, img)
            with open(file, &#39;w+&#39;) as fw:
                fw.write(file)
        elif params == &#39;pillow&#39;:
            pil_image = Image.fromarray(img.to_np)
            pil_image.save(file_path)
        else:
            try:
                import cv2
                cv2.imwrite(file_path, img.to_np, params)
            except ImportError:
                Log(ERROR, f&#34;import cv2 error while using imwrite save image with params {params}.&#34;)


    def __del__(self):
        if hasattr(self, &#39;_channel_desc&#39;):
            ret = acl.media.dvpp_destroy_channel(self._channel_desc)
            assert ret == ACL_SUCCESS, f&#34;dvpp destroy channel failed, return {ret}.&#34;

            ret = acl.media.dvpp_destroy_channel_desc(self._channel_desc)
            assert ret == ACL_SUCCESS, f&#34;dvpp destroy channel desc failed, return {ret}.&#34;</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="ascend.Image.bbox_resize"><code class="name flex">
<span>def <span class="ident">bbox_resize</span></span>(<span>self, img, bboxes, sizes, inner_resize=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Clip the bboxes image and resize to specified size.</p>
<p>2 steps:
clip the bboxes image -&gt; resize croped image.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image to be cliped.</dd>
<dt><strong><code>bboxes</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Shape (k, 4) or (4, ), location of cropped bboxes.</dd>
<dt><strong><code>sizes</code></strong> :&ensp;<code>int</code></dt>
<dd>Shape (k, 2) or (2, ), scale sizes of bboxes.</dd>
<dt><strong><code>inner_resize</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Use dvpp auto resize function to resize croped boxes</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code> or <code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The cropped and resized image patches.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
sizes = np.array([[300, 300], [400, 400]])
yuv_croped = Img.bbox_resize(img, bboxes, sizes)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L850-L954" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def bbox_resize(self, img, bboxes, sizes, inner_resize=True):
    &#34;&#34;&#34;Clip the bboxes image and resize to specified size.

    2 steps:  clip the bboxes image -&gt; resize croped image.

    Args:
        img (AscendArray): Image to be cliped.
        bboxes (ndarray): Shape (k, 4) or (4, ), location of cropped bboxes.
        sizes (int): Shape (k, 2) or (2, ), scale sizes of bboxes.
        inner_resize (bool, optional): Use dvpp auto resize function to resize croped boxes

    Returns:
        list[AscendArray] or AscendArray: The cropped and resized image patches.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
    sizes = np.array([[300, 300], [400, 400]])
    yuv_croped = Img.bbox_resize(img, bboxes, sizes)
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray, but we got {type(img)}.&#34;)

    # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
    if img.format &lt; 0 or img.format &gt; 17:
        raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
            [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

    if not isinstance(bboxes, np.ndarray):
        raise TypeError(f&#34;Input bboxes expects an np.ndarray, but given {type(bboxes)}.&#34;)

    if not isinstance(sizes, np.ndarray):
        raise TypeError(f&#34;Input sizes expects an np.ndarray, but given {type(sizes)}.&#34;)

    if self._channel_desc is None:
        raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

    assert sizes.shape[-1] == 2, f&#34;Input sizes dim 2 must be 2.&#34;
    if sizes.ndim == 2 and sizes.shape[0] != bboxes.shape[0]:
        raise ValueError(f&#34;Input sizes&#39;s shape expects same to bboxes.&#34;)

    # step 1: caculate the cliped bbox shape
    _bboxes = bboxes[None, ...] if bboxes.ndim == 1 else bboxes
    scaled_bboxes = bbox_scaling(_bboxes, 1.0).astype(np.int32)
    clipped_bbox = _align_roi(scaled_bboxes, img)

    # align original image 
    src_img, shape = _align_img(img, func=&#39;crop&#39;)

    # step 2: input desc assembile, only process one image.
    image_inst = PicDesc([src_img], shape)
    roi_n_list = [clipped_bbox.shape[0]]

    # step 3: clip bboxes of image
    bboxes, roi_list = [], []
    _sizes = sizes[None, ...].tolist() if sizes.ndim == 1 else sizes.tolist()
    for i in range(clipped_bbox.shape[0]):
        x1, y1, x2, y2 = clipped_bbox[i, :].tolist()

        # align w and h, and calc memory size of output box image
        if inner_resize:
            dst_image = _create_align_img(_sizes[i][0], _sizes[i][1], format=img.format, func=&#39;crop&#39;)
        else:
            dst_image = _create_align_img(x2 - x1, y2 - y1, format=img.format, func=&#39;crop&#39;)
        bboxes.append(dst_image)

        # create roi description
        roi_conf = acl.media.dvpp_create_roi_config(x1, x2, y1, y2)
        roi_list.append(roi_conf)

    # create output image desc and bind it with a output AscendArray object
    bboxes_inst = PicDesc(bboxes)

    # step 4: crop processing
    _, ret = acl.media.dvpp_vpc_batch_crop_async(
                                        self._channel_desc,
                                        image_inst.desc, 
                                        roi_n_list,
                                        bboxes_inst.desc,
                                        roi_list,
                                        self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_vpc_crop_async, return {ret}.&#34;)

    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to crop image in synchronize_stream, return {ret}.&#34;)
    
    for roi in roi_list:
        ret = acl.media.dvpp_destroy_roi_config(roi)
        assert ret == ACL_SUCCESS, \
            ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

    del (image_inst, bboxes_inst)
    Log(INFO, &#39;vpc crop process success&#39;)

    if not inner_resize:
        res_img = []
        for bbox in bboxes:
            res_img.append(self.imresize(bbox, _sizes[i]))
        return res_img

    return bboxes</code></pre>
</details>
</dd>
<dt id="ascend.Image.imcrop"><code class="name flex">
<span>def <span class="ident">imcrop</span></span>(<span>self, img, bboxes, scale=1.0)</span>
</code></dt>
<dd>
<div class="desc"><p>Crop image patches, and resize bboxes.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image to be cropped.</dd>
<dt><strong><code>bboxes</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Shape (k, 4) or (4,), location of cropped bboxes.</dd>
<dt><strong><code>scale</code></strong> :&ensp;<code>float</code>, optional</dt>
<dd>Scale ratio of bboxes, the default value 1.0 means no padding.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>list[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code> or <code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The cropped image patches.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
yuv_croped = Img.imcrop(img, bboxes)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L759-L848" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imcrop(self, img, bboxes, scale=1.0):
    &#34;&#34;&#34;Crop image patches, and resize bboxes.

    Args:
        img (AscendArray): Image to be cropped.
        bboxes (ndarray): Shape (k, 4) or (4,), location of cropped bboxes.
        scale (float, optional): Scale ratio of bboxes, the default value 1.0 means no padding.

    Returns:
        list[AscendArray] or AscendArray: The cropped image patches.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    bboxes = np.array([[20, 40, 159, 259],[400, 200, 479, 419]], dtype=int)
    yuv_croped = Img.imcrop(img, bboxes)
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray, but we got a {type(img)}.&#34;)

    # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
    if img.format &lt; 0 or img.format &gt; 17:
        raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
            [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

    if not isinstance(bboxes, np.ndarray):
        raise TypeError(f&#34;Input bbox expects an np.ndarray, but we got a {type(bboxes)}.&#34;)

    if self._channel_desc is None:
        raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

    # step 1: caculate the cliped bbox shape
    _bboxes = bboxes[None, ...] if bboxes.ndim == 1 else bboxes
    scaled_bboxes = bbox_scaling(_bboxes, scale).astype(np.int32)
    clipped_bbox = _align_roi(scaled_bboxes, img)
    
    # align original image
    src_img, shape = _align_img(img, func=&#39;crop&#39;)

    # step 2: input desc assembling, only process one image.
    image_inst = PicDesc([src_img], shape)
    roi_n_list = [clipped_bbox.shape[0]]

    # step 3: clip bboxes of image
    bboxes, roi_list = [], []
    for i in range(clipped_bbox.shape[0]):
        x1, y1, x2, y2 = clipped_bbox[i, :].tolist()
        
        # create a bbox(a AscendArray object) and bind with dvpp memory
        dst_image = _create_align_img(x2 - x1, y2 - y1, format=img.format, func=&#39;crop&#39;)
        bboxes.append(dst_image)

        # create roi description
        roi_conf = acl.media.dvpp_create_roi_config(x1, x2, y1, y2)
        roi_list.append(roi_conf)

    # create output image desc and bind it with a output AscendArray object
    bboxes_inst = PicDesc(bboxes)

    # step 4: crop processing
    _, ret = acl.media.dvpp_vpc_batch_crop_async(
                                        self._channel_desc,
                                        image_inst.desc, 
                                        roi_n_list,
                                        bboxes_inst.desc,
                                        roi_list,
                                        self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_vpc_crop_async, return {ret}.&#34;)

    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to crop image in synchronize_stream, return {ret}.&#34;)
    
    for roi in roi_list:
        ret = acl.media.dvpp_destroy_roi_config(roi)
        assert ret == ACL_SUCCESS, \
            ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

    del image_inst, bboxes_inst
    Log(INFO, &#39;vpc crop process success&#39;)

    if not np.isclose(scale, 1.0, rtol=1e-2, atol=1e-03):
        res_img = []
        for bbox in bboxes:
            res_img.append(self.imrescale(bbox, scale))
        return res_img

    return bboxes</code></pre>
</details>
</dd>
<dt id="ascend.Image.imcrop_paste"><code class="name flex">
<span>def <span class="ident">imcrop_paste</span></span>(<span>self, src_img, dst_img, crop_bbox, paste_bbox)</span>
</code></dt>
<dd>
<div class="desc"><p>Crop a bbox from src image and paste the cropped bbox to dst image</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>src_img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Input src image(AscendArray) to be croped.</dd>
<dt><strong><code>dst_img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Input dst image(AscendArray) to be pasted.</dd>
<dt><strong><code>crop_bbox</code></strong> :&ensp;<code>np.ndarray</code></dt>
<dd>Shape (4, ) or (n, 4), location of cropped bboxe, data arrangement,
np.array([startx, starty, endx, endy], dtype=int).</dd>
<dt><strong><code>paste_bbox</code></strong> :&ensp;<code>np.ndarray</code></dt>
<dd>Shape (4, ) or (n, 4), location of pasted bboxe, data arrangement
same to crop_bbox.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Dest image after cropping and pasting.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
crop_bbox = np.array([40, 30, 140, 230], dtype='int32')
paste_bbox = np.array([70, 80, 170, 280], dtype='int32')
Img.imcrop_paste(yuv_src, yuv_dst, crop_bbox, paste_bbox)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L957-L1046" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imcrop_paste(self, src_img, dst_img, crop_bbox, paste_bbox):
    &#34;&#34;&#34;Crop a bbox from src image and paste the cropped bbox to dst image

    Args:
        src_img (AscendArray): Input src image(AscendArray) to be croped.
        dst_img (AscendArray): Input dst image(AscendArray) to be pasted.
        crop_bbox (np.ndarray): Shape (4, ) or (n, 4), location of cropped bboxe, data arrangement,
            np.array([startx, starty, endx, endy], dtype=int).
        paste_bbox (np.ndarray): Shape (4, ) or (n, 4), location of pasted bboxe, data arrangement
            same to crop_bbox.

    Returns:
        AscendArray: Dest image after cropping and pasting.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    crop_bbox = np.array([40, 30, 140, 230], dtype=&#39;int32&#39;)
    paste_bbox = np.array([70, 80, 170, 280], dtype=&#39;int32&#39;)
    Img.imcrop_paste(yuv_src, yuv_dst, crop_bbox, paste_bbox)
    ```
    &#34;&#34;&#34;

    if not isinstance(src_img, AscendArray):
        raise TypeError(f&#34;Input src_img expects an AscendArray, but we got a {type(src_img)}.&#34;)

    if not isinstance(dst_img, AscendArray):
        raise TypeError(f&#34;Input dst_img expects an AscendArray, but we got a {type(dst_img)}.&#34;)

    if not isinstance(crop_bbox, np.ndarray):
        raise TypeError(f&#34;Input bbox expects an np.ndarray, but we got a {type(crop_bbox)}.&#34;)

    if not isinstance(paste_bbox, np.ndarray):
        raise TypeError(f&#34;Input bbox expects an np.ndarray, but we got a {type(crop_bbox)}.&#34;)

    if crop_bbox.shape[-1] != 4 or paste_bbox.shape[-1] != 4:
        raise ValueError(f&#34;Input crop_bbox or paste_bbox column dim should be 4.&#34;)

    if crop_bbox.shape[0] != paste_bbox.shape[0]:
        raise ValueError(f&#34;Input crop_bbox and paste_bbox should have same number bbox.&#34;)

    # step 1: clip input bbox to fit image, make startx and starty to even and endx and endy to odd
    cbbox = _align_roi(crop_bbox, src_img).tolist()
    pbbox = _align_roi(paste_bbox, dst_img, is_paste=True).tolist()

    # step 2: align original image
    crop_img, shape_c = _align_img(src_img, func=&#39;crop&#39;)
    paste_img, shape_p = _align_img(dst_img, func=&#39;crop&#39;)

    # step 3: create output image desc and bind it with a output AscendArray object
    src_desc = PicDesc([crop_img], shape_c)
    dst_desc = PicDesc([paste_img] * len(pbbox), shape_p)

    # step 4: startx of paste box aligned to 16 and append crop/paste roi to list
    crop_conf_list, past_conf_list = [], []
    for i in range(len(pbbox)):
        crop_conf = acl.media.dvpp_create_roi_config(
            cbbox[i][0], cbbox[i][2], cbbox[i][1], cbbox[i][3])
        past_conf = acl.media.dvpp_create_roi_config(
            pbbox[i][0], pbbox[i][2], pbbox[i][1], pbbox[i][3])
        crop_conf_list.append(crop_conf)
        past_conf_list.append(past_conf)

    # step 5: do crop and paste
    _, ret = acl.media.dvpp_vpc_batch_crop_and_paste_async(self._channel_desc,
                                                        src_desc.desc,
                                                        [len(pbbox)], 
                                                        dst_desc.desc,
                                                        crop_conf_list, 
                                                        past_conf_list,
                                                        self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_vpc_batch_crop_and_paste_async, return {ret}.&#34;)

    # step 6: synchronize stream and finish crop and paste 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to crop and paste image in synchronize_stream, return {ret}.&#34;)

    for conf in crop_conf_list:
        ret = acl.media.dvpp_destroy_roi_config(conf)
        assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;

    for conf in past_conf_list:
        ret = acl.media.dvpp_destroy_roi_config(conf)
        assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;

    del (crop_img, src_desc, dst_desc)
    Log(INFO, &#39;crop and paste process success&#39;)
    return paste_img</code></pre>
</details>
</dd>
<dt id="ascend.Image.imdecode"><code class="name flex">
<span>def <span class="ident">imdecode</span></span>(<span>self, array, format=1, return_shape=False)</span>
</code></dt>
<dd>
<div class="desc"><p>imdecode(array, format) -&gt; retval</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The function imdecode reads an image from the specified numpy ndarray and decode to yuv image.
See www.hiascend.com for the list of supported format.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>array</code></strong> :&ensp;<code>ndarray</code></dt>
<dd>Input numpy ndarray.</dd>
<dt><strong><code>format</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>The supported decode image format. Defaults to PIXEL_FORMAT_YUV_SEMIPLANAR_420.</dd>
<dt><strong><code>return_shape</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Return original shape(h, w, c) of image.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a> </code></dt>
<dd>The decoded image(AscendArray obj)</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
data = np.fromfile('./image.jpg', dtype=np.uint8)
image = Img.imdecode(data)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L308-L406" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imdecode(self, array, format=PIXEL_FORMAT_YUV_SEMIPLANAR_420, return_shape=False):
    &#34;&#34;&#34; imdecode(array, format) -&gt; retval
    
    .. note::
        The function imdecode reads an image from the specified numpy ndarray and decode to yuv image.
        See www.hiascend.com for the list of supported format.

    Args:
        array (ndarray): Input numpy ndarray.
        format (int, optional): The supported decode image format. Defaults to PIXEL_FORMAT_YUV_SEMIPLANAR_420.
        return_shape (bool, optional): Return original shape(h, w, c) of image.

    Returns:
        AscendArray : The decoded image(AscendArray obj)

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    data = np.fromfile(&#39;./image.jpg&#39;, dtype=np.uint8)
    image = Img.imdecode(data)
    ```
    &#34;&#34;&#34;
    if not isinstance(array, np.ndarray):
        raise TypeError(f&#34;Input array expects an np.ndarray object, but got {type(array)}.&#34;)

    img_ptr = acl.util.numpy_to_ptr(array)

    w, h, c, ret = acl.media.dvpp_jpeg_get_image_info(img_ptr, array.nbytes)
    if ret == ACL_SUCCESS:
        decoder = &#39;jpg&#39;
    else:
        w, h, c, ret = acl.media.dvpp_png_get_image_info(img_ptr, array.nbytes)
        assert ret ==ACL_SUCCESS, f&#34;Get input image&#39;s info failed, return {ret}.&#34;
        decoder = &#39;png&#39;

    constrain_ = 8192 if decoder == &#39;jpg&#39; else 4096
    if w &lt; 32 or w &gt; constrain_:
        raise ValueError(f&#34;Input image&#39;s width out of range [32, {constrain_}].&#34;)

    if h &lt; 32 or h &gt; constrain_:
        raise ValueError(f&#34;Input image&#39;s height out of range [32, {constrain_}].&#34;)

    if decoder == &#39;jpg&#39; and format not in [
        PIXEL_FORMAT_YUV_SEMIPLANAR_420,
        PIXEL_FORMAT_YVU_SEMIPLANAR_420,
        PIXEL_FORMAT_YVU_SEMIPLANAR_422,
        PIXEL_FORMAT_YVU_SEMIPLANAR_444
        ]:
        raise ValueError(f&#34;Input decode {format} is invalid, this format is unsupport.&#34;)

    if decoder ==&#39;png&#39; and format not in [
        PIXEL_FORMAT_RGB_888,
        PIXEL_FORMAT_BGR_888,
        PIXEL_FORMAT_ARGB_8888,
        PIXEL_FORMAT_ABGR_8888,
        PIXEL_FORMAT_RGBA_8888,
        PIXEL_FORMAT_BGRA_8888
        ]:
        raise ValueError(f&#34;Input decode {format} is invalid, this format is unsupport.&#34;)

    if self._channel_desc is None:
        raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

    # clone input image to device
    data = AscendArray.clone(array, context=self.context, flag=&#34;DVPP&#34;)

    image = _create_align_img(w, h, format=format, func=&#39;jpegd&#39; if decoder == &#39;jpg&#39; else &#39;pngd&#39;)

    # create output image desc and bind it with a output AscendArray object
    pic_inst = PicDesc(image, (w, h))

    # do jpeg decode
    if decoder == &#39;jpg&#39;:
        ret = acl.media.dvpp_jpeg_decode_async(self._channel_desc,
                                            data.ascend_data,
                                            data.nbytes,
                                            pic_inst.desc,
                                            self.stream)
        assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_jpeg_decode_async, return {ret}.&#34;
    else:
        ret = acl.media.dvpp_png_decode_async(self._channel_desc,
                                            data.ascend_data,
                                            data.nbytes,
                                            pic_inst.desc,
                                            self.stream)
        assert ret == ACL_SUCCESS, f&#34;Failed to do dvpp_png_decode_async, return {ret}.&#34;
    
    # finish jpeg image decode
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to decode jpeg image in synchronize_stream, return {ret}.&#34;)

    # release the unused resource in future
    del (data, pic_inst)
    Log(INFO, &#39;imdecode success.&#39;)
    if return_shape:
        return image, (h, w, c)
    else:
        return image</code></pre>
</details>
</dd>
<dt id="ascend.Image.imencode"><code class="name flex">
<span>def <span class="ident">imencode</span></span>(<span>self, ext, img, params=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Encodes an image into a memory buffer.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The function imencode compresses the image and stores it in the memory buffer
that is resized to fit the result. See www.hiascend.com for the list of
supported format and flags description.</p>
</div>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>ext</code></strong> :&ensp;<code>str</code></dt>
<dd>File extension that defines the output format.</dd>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image to be written</dd>
<dt><strong><code>params</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Format-specific parameters, not use.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a> </code></dt>
<dd>Output buffer resized to fit the compressed image.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">img_encode = img.imencode('.jpg', yuv_img)
str_encode = np.array(img_encode).tostring()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L409-L496" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imencode(self, ext, img, params=None):
    &#34;&#34;&#34; Encodes an image into a memory buffer.
     
    .. note::
        The function imencode compresses the image and stores it in the memory buffer 
        that is resized to fit the result. See www.hiascend.com for the list of 
        supported format and flags description.
     
    Args:
        ext (str): File extension that defines the output format.
        img (AscendArray): Image to be written
        params (str, optional): Format-specific parameters, not use.

    Returns:
        AscendArray : Output buffer resized to fit the compressed image.
    
    Typical usage example:
    ```python
    img_encode = img.imencode(&#39;.jpg&#39;, yuv_img)
    str_encode = np.array(img_encode).tostring()
    ```
    &#34;&#34;&#34;
    if ext not in IMG_EXT_ENC:
        raise TypeError(f&#34;Input ext expects {IMG_EXT_ENC}, but got {ext}.&#34;)

    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

    if img.format not in [
        PIXEL_FORMAT_YUV_SEMIPLANAR_420,
        PIXEL_FORMAT_YVU_SEMIPLANAR_420,
        PIXEL_FORMAT_YUYV_PACKED_422, 
        PIXEL_FORMAT_UYVY_PACKED_422, 
        PIXEL_FORMAT_YVYU_PACKED_422,
        PIXEL_FORMAT_VYUY_PACKED_422
        ]:
        raise ValueError(f&#34;Encode img&#39;s format {img.format} is invalid, this format not support.&#34;)

    if self._channel_desc is None:
        raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

    src_img, shape = _align_img(img, func=&#39;encode&#39;)

    # create input image desc and bind it with a input AscendArray object
    src_inst = PicDesc(src_img, shape)

    # create a jpeg image encode configurate
    config = acl.media.dvpp_create_jpege_config()
    ret = acl.media.dvpp_set_jpege_config_level(config, 100)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Set jpege config level failed, return {ret}.&#34;)

    # predict out buffer size according to image desc
    buff_size, ret = acl.media.dvpp_jpeg_predict_enc_size(src_inst.desc, config)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;jpeg predict encode size failed, return {ret}.&#34;)

    # config out buffer of encode
    out_size = np.array([buff_size], dtype=np.int32)
    size_ptr = acl.util.numpy_to_ptr(out_size)
    enc_jpg = AscendArray((buff_size,), np.dtype(&#39;uint8&#39;), format=img.format, flag=&#39;DVPP&#39;)
    
    # do jpeg decode
    ret = acl.media.dvpp_jpeg_encode_async(self._channel_desc,
                                           src_inst.desc,
                                           enc_jpg.ascend_data,
                                           size_ptr,
                                           config,
                                           self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_jpeg_encode_async, return {ret}.&#34;)
    
    # finish jpeg image decode
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to encode jpeg image in synchronize_stream, return {ret}.&#34;)

    # trans AscendArray data to numpy array
    jpeg_img = enc_jpg.to_np

    # release the unused resource in future
    del (src_inst, src_img, enc_jpg)
    Log(INFO, &#39;imdecode success.&#39;)

    ret = acl.media.dvpp_destroy_jpege_config(config)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;destroy jpege config failed, return {ret}.&#34;)
    return jpeg_img</code></pre>
</details>
</dd>
<dt id="ascend.Image.imflip"><code class="name flex">
<span>def <span class="ident">imflip</span></span>(<span>self, img, direction='horizontal')</span>
</code></dt>
<dd>
<div class="desc"><p>Flip an image horizontally or vertically.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image to be flipped.</dd>
<dt><strong><code>direction</code></strong> :&ensp;<code>str</code></dt>
<dd>The flip direction, either "horizontal" or "vertical" or "diagonal".</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The flipped image.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
im_flip = Img.imflip(img, direction='horizontal')
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L661-L694" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imflip(self, img, direction=&#39;horizontal&#39;):
    &#34;&#34;&#34;Flip an image horizontally or vertically.

    Args:
        img (AscendArray): Image to be flipped.
        direction (str): The flip direction, either &#34;horizontal&#34; or &#34;vertical&#34; or &#34;diagonal&#34;.

    Returns:
        AscendArray: The flipped image.
    
    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    im_flip = Img.imflip(img, direction=&#39;horizontal&#39;)
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

    # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
    if img.format &lt; 0 or img.format &gt; 17:
        raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
            [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

    assert direction in [&#39;horizontal&#39;, &#39;vertical&#39;, &#39;diagonal&#39;]

    arr = img.to_np

    if direction == &#39;horizontal&#39;:
        return AscendArray.clone(np.flip(arr, axis=1))
    elif direction == &#39;vertical&#39;:
        return AscendArray.clone(np.flip(arr, axis=0))
    else:
        return AscendArray.clone(np.flip(arr, axis=(0, 1)))</code></pre>
</details>
</dd>
<dt id="ascend.Image.impad"><code class="name flex">
<span>def <span class="ident">impad</span></span>(<span>self, img, shape=None, padding=None, pad_val=0, padding_mode='constant')</span>
</code></dt>
<dd>
<div class="desc"><p>Pad the given image to a certain shape or pad on all sides with
specified padding mode and padding value.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image to be padded.</dd>
<dt><strong><code>shape</code></strong> :&ensp;<code>tuple[int]</code></dt>
<dd>Expected padding shape (h, w). Default: None.</dd>
<dt><strong><code>padding</code></strong> :&ensp;<code>int</code> or <code>tuple[int]</code></dt>
<dd>Padding on each border. If a single int is provided this
is used to pad all borders. If tuple of length 2 is provided this is the padding
on left/right and top/bottom respectively. If a tuple of length 4 is provided
this is the padding for the [left, top, right and bottom] borders respectively.
Default: None. Note that <code>shape</code> and <code>padding</code> can not be both set.</dd>
<dt><strong><code>pad_val</code></strong> :&ensp;<code>Number</code></dt>
<dd>Values to be filled in padding areas when padding_mode is
'constant'. Default: 0.</dd>
<dt><strong><code>padding_mode</code></strong> :&ensp;<code>str</code></dt>
<dd>
<p>Type of padding. Only support: constant. Default: constant.</p>
<ul>
<li>constant: pads with a constant value, this value is specified with pad_val.</li>
</ul>
</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a> </code></dt>
<dd>The padded image.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
yuv_pad = Img.impad(img, padding=(20, 50, 100, 200), pad_val=128)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L1048-L1153" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def impad(self, img, shape=None, padding=None, pad_val=0, padding_mode=&#39;constant&#39;):
    &#34;&#34;&#34;Pad the given image to a certain shape or pad on all sides with
        specified padding mode and padding value.

    Args:
        img (AscendArray): Image to be padded.
        shape (tuple[int]): Expected padding shape (h, w). Default: None.
        padding (int or tuple[int]): Padding on each border. If a single int is provided this 
            is used to pad all borders. If tuple of length 2 is provided this is the padding 
            on left/right and top/bottom respectively. If a tuple of length 4 is provided 
            this is the padding for the [left, top, right and bottom] borders respectively.
            Default: None. Note that `shape` and `padding` can not be both set.
        pad_val (Number): Values to be filled in padding areas when padding_mode is 
            &#39;constant&#39;. Default: 0.
        padding_mode (str): Type of padding. Only support: constant. Default: constant.

            - constant: pads with a constant value, this value is specified with pad_val.

    Returns:
        AscendArray : The padded image.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    yuv_pad = Img.impad(img, padding=(20, 50, 100, 200), pad_val=128)
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray, but we got a {type(img)}.&#34;)

    if shape and not isinstance(shape, tuple):
        raise TypeError(f&#34;Input shape expects an tuple, but we got a {type(shape)}.&#34;)

    if padding and not isinstance(padding, (int, tuple)):
        raise TypeError(f&#34;Input padding expects an int or tuple, but we got a {type(padding)}.&#34;)

    if padding_mode not in [&#39;constant&#39;]:
        raise TypeError(f&#34;Input padding_mode expects in [&#39;constant&#39;], but we got {padding_mode}.&#34;)

    assert (shape is not None) ^ (padding is not None), \
            f&#34;Input `shape` and `padding` can not be both set.&#34;

    # get the truth h and w of image.
    if img.format in yuv420:
        h, w = (img.shape[0] * 2 // 3, img.shape[1])
    else:
        h, w = img.shape[:2]

    if shape is not None:
        padding = (0, 0, shape[1] - w, shape[0] - h)

    if isinstance(padding, tuple) and len(padding) in [2, 4]:
        if len(padding) == 2:
            padding = (padding[0], padding[1], padding[0], padding[1])
    elif isinstance(padding, numbers.Number):
        padding = (padding, padding, padding, padding)
    else:
        raise ValueError(&#39;Padding must be a int or a 2, or 4 element tuple.&#39;
                        f&#39;But received {padding}&#39;)

    # align original image shape and create a output to save padding result.
    src_img, src_shape = _align_img(img)
    dst_w, dst_h = padding[0] + w + padding[2], padding[1] + h + padding[3]
    dst_img = _create_align_img(dst_w, dst_h, format=img.format)

    # set the padding result&#39;s memory with pad_val
    Memory.reset(dst_img.ascend_data, dst_img.nbytes, pad_val)

    # create output image desc and bind it with a output AscendArray object
    src_desc = PicDesc(src_img, src_shape)
    dst_desc = PicDesc(dst_img, (dst_h, dst_w))

    # paste area startx, starty, endx, endy, and align startx with 16
    startx = aligned(padding[0], aligned=&#39;w&#39;)
    starty = padding[1] &gt;&gt; 1 &lt;&lt; 1
    endx = ((startx + w) &gt;&gt; 1 &lt;&lt; 1) - 1
    endy = ((padding[1] + h) &gt;&gt; 1 &lt;&lt; 1) - 1

    # create roi description
    roi_conf = acl.media.dvpp_create_roi_config(0, (w &gt;&gt; 1 &lt;&lt; 1) - 1, 0, (h &gt;&gt; 1 &lt;&lt; 1) - 1)
    pst_conf = acl.media.dvpp_create_roi_config(startx, endx, starty, endy)

    ret = acl.media.dvpp_vpc_crop_and_paste_async(self._channel_desc,
                                                  src_desc.desc,
                                                  dst_desc.desc,
                                                  roi_conf,
                                                  pst_conf,
                                                  self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_vpc_crop_and_paste_async, return {ret}.&#34;)

    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to crop and paste image in synchronize_stream, return {ret}.&#34;)

    ret = acl.media.dvpp_destroy_roi_config(roi_conf)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

    ret = acl.media.dvpp_destroy_roi_config(pst_conf)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_destroy_resize_config, return {ret}.&#34;)

    del (src_img, src_desc, dst_desc)
    Log(INFO, &#39;image padding process success&#39;)
    return dst_img</code></pre>
</details>
</dd>
<dt id="ascend.Image.imread"><code class="name flex">
<span>def <span class="ident">imread</span></span>(<span>self, img_or_path, flag='color', channel_order='bgr', backend='ascend', keep_shape=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Read an image.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img_or_path</code></strong> :&ensp;<code>ndarray</code> or <code>str</code> or <code>Path</code></dt>
<dd>Either a numpy array or str or pathlib.Path. If
it is a numpy array (loaded image), then it will be returned as is.</dd>
<dt><strong><code>flag</code></strong> :&ensp;<code>str</code></dt>
<dd>Flags specifying the color type of a loaded image, candidates are <code>color</code>,
<code>grayscale</code> and <code>unchanged</code>. It only work for <code>cv2</code> and <code>pillow</code>.</dd>
<dt><strong><code>channel_order</code></strong> :&ensp;<code>str</code></dt>
<dd>Order of channel, candidates are <code>bgr</code> and <code>rgb</code>, not work for ascend.</dd>
<dt><strong><code>backend</code></strong> :&ensp;<code>str</code></dt>
<dd>The image decoding backend type. Options are <code>cv2</code>, <code>pillow</code>, <code><a title="ascend" href="#ascend">ascend</a></code>.
Default: <code><a title="ascend" href="#ascend">ascend</a></code>.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Loaded image array.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
yuv = Img.imread('./image.jpg')
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L1155-L1221" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imread(self, img_or_path, flag=&#39;color&#39;, channel_order=&#39;bgr&#39;, backend=&#39;ascend&#39;, keep_shape=False):
    &#34;&#34;&#34;Read an image.

    Args:
        img_or_path (ndarray or str or Path): Either a numpy array or str or pathlib.Path. If 
            it is a numpy array (loaded image), then it will be returned as is.
        flag (str): Flags specifying the color type of a loaded image, candidates are `color`, 
            `grayscale` and `unchanged`. It only work for `cv2` and `pillow`.
        channel_order (str): Order of channel, candidates are `bgr` and `rgb`, not work for ascend.
        backend (str): The image decoding backend type. Options are `cv2`, `pillow`, `ascend`. 
            Default: `ascend`.

    Returns:
        AscendArray: Loaded image array.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    yuv = Img.imread(&#39;./image.jpg&#39;)
    ```
    &#34;&#34;&#34;
    if backend not in [&#39;cv2&#39;, &#39;pillow&#39;, &#39;ascend&#39;]:
        raise ValueError(f&#39;backend: {backend} is not supported. Supported &#34;backends are &#39;
                        &#34;&#39;cv2&#39;, &#39;pillow&#39;, &#39;ascend&#39;.&#34;)

    if backend == &#39;cv2&#39;:
        try:
            import cv2
            imread_flags = {
                &#39;color&#39;: cv2.IMREAD_COLOR,
                &#39;grayscale&#39;: cv2.IMREAD_GRAYSCALE,
                &#39;unchanged&#39;: cv2.IMREAD_UNCHANGED
            }
        except ImportError:
            Log(ERROR, &#34;import cv2 error while using imread with backend &#39;cv2&#39;.&#34;)
            return

    if isinstance(img_or_path, Path):
        img_or_path = str(img_or_path)

    if isinstance(img_or_path, np.ndarray): 
        if keep_shape:           
            decode_img, ori_shape = self.imdecode(img_or_path, return_shape=True)
            return self.imcrop(decode_img, np.array([0, 0, ori_shape[1] - 1, ori_shape[0] - 1]))[0]
        else:
            return self.imdecode(img_or_path)
    elif is_str(img_or_path):
        check_file_exist(img_or_path, f&#39;img file does not exist: {img_or_path}&#39;)
        if backend == &#39;pillow&#39;:
            img = Image.open(img_or_path)
            img = _pillow2array(img, flag, channel_order)
            return AscendArray.clone(img)
        elif backend == &#39;cv2&#39;:
            flag = imread_flags[flag] if is_str(flag) else flag
            img = cv2.imread(img_or_path, flag)
            if flag == cv2.IMREAD_COLOR and channel_order == &#39;rgb&#39;:
                cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
            return AscendArray.clone(img)
        else:
            array = np.fromfile(img_or_path, dtype=np.uint8)
            if keep_shape:
                decode_img, ori_shape = self.imdecode(array, return_shape=True)
                return self.imcrop(decode_img, np.array([0, 0, ori_shape[1] - 1, ori_shape[0] - 1]))[0]
            else:
                return self.imdecode(array)
    else:
        raise TypeError(&#39;&#34;img&#34; must be a numpy array or a str or a pathlib.Path object&#39;)</code></pre>
</details>
</dd>
<dt id="ascend.Image.imrescale"><code class="name flex">
<span>def <span class="ident">imrescale</span></span>(<span>self, img, scale, interpolation='huawei', return_shape=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Resize image while keeping the aspect ratio.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code>AsecendArray</code></dt>
<dd>The input image.</dd>
<dt><strong><code>scale</code></strong> :&ensp;<code>float, tuple[int]</code></dt>
<dd>The scaling factor or maximum size. If it is a float
number, then the image will be rescaled by this factor, else if it is a tuple
of 2 integers, then the image will be rescaled as large as possible within
the scale.</dd>
<dt><strong><code>interpolation</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Same as :func:<code>imresize</code>.</dd>
<dt><strong><code>return_shape</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Return scale shape not aligned.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>AsecendArray </code></dt>
<dd>The rescaled image.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
yuv_rescale1 = Img.imrescale(yuv, 0.3)
yuv_rescale2 = Img.imrescale(yuv, (320, 540))
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L600-L659" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imrescale(self, img, scale, interpolation=&#39;huawei&#39;, return_shape=False):
    &#34;&#34;&#34;Resize image while keeping the aspect ratio.

    Args:
        img (AsecendArray): The input image.
        scale (float, tuple[int]): The scaling factor or maximum size. If it is a float 
            number, then the image will be rescaled by this factor, else if it is a tuple 
            of 2 integers, then the image will be rescaled as large as possible within 
            the scale.
        interpolation (str, optional): Same as :func:`imresize`.
        return_shape (bool, optional): Return scale shape not aligned.

    Returns:
        AsecendArray : The rescaled image.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    yuv_rescale1 = Img.imrescale(yuv, 0.3)
    yuv_rescale2 = Img.imrescale(yuv, (320, 540))
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

    # valid format is in range [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)]
    if img.format &lt; 0 or img.format &gt; 17:
        raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
            [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

    # get the truth h and w of image.
    if img.format in yuv420:
        h, w = (img.shape[0] * 2 // 3, img.shape[1])
    else:
        h, w = img.shape[:2]

    if isinstance(scale, (float, int)):
        if scale &lt;= 0:
            raise ValueError(f&#39;Invalid scale {scale}, must be positive.&#39;)  
        scale_factor = scale
    elif isinstance(scale, tuple):
        max_long_edge = max(scale)
        max_short_edge = min(scale)

        # find the maximum rescale ratio, and the resized shape should be valid.
        scale_factor = min(max_long_edge/max(h, w), max_short_edge/min(h, w))
    else:
        raise TypeError(
            f&#39;Scale must be a number or tuple of int, but got {type(scale)}&#39;)

    # caculate new rescaled size according to scale_factor 
    new_size = _scale_size((w, h), scale_factor)

    # do resize
    rescaled_img = self.imresize(img, new_size, interpolation=interpolation)

    if return_shape:
        return rescaled_img, new_size
    else:
        return rescaled_img</code></pre>
</details>
</dd>
<dt id="ascend.Image.imresize"><code class="name flex">
<span>def <span class="ident">imresize</span></span>(<span>self, img, dsize, interpolation='huawei')</span>
</code></dt>
<dd>
<div class="desc"><p>imresize(array, img, dsize, interpolation='huawei') -&gt; retval</p>
<p>To shrink an image, it will generally look best with #INTER_AREA interpolation</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Input image</dd>
<dt><strong><code>dsize</code></strong> :&ensp;<code>tuple</code></dt>
<dd>The output image size (tuple(w, h));</dd>
<dt><strong><code>interpolation</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>The interpolation method, its default method is researched
by ourself.. Defaults to 'huawei'.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The resized image</dd>
</dl>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The function resize resizes the image img down to or up to the specified size. Note that the
initial dst type or size are not taken into account. Instead, the size and type are derived from
the img, dsize.</p>
</div>
<p>you may call the function as follows:</p>
<pre><code class="language-python"># explicitly specify dsize (tuple[int]): Target size (w, h).
imresize(img, dsize, interpolation)
</code></pre>
<p>If you want to decimate the image by factor of 2 in each direction, you can call the function this way:</p>
<pre><code class="language-python"># specify the element w and h of the destination image size.
imresize(img, (w//2, h//2), interpolation)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L499-L597" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imresize(self, img, dsize, interpolation=&#39;huawei&#39;):
    &#34;&#34;&#34;imresize(array, img, dsize, interpolation=&#39;huawei&#39;) -&gt; retval

    To shrink an image, it will generally look best with #INTER_AREA interpolation

    Args:
        img (AscendArray): Input image
        dsize (tuple): The output image size (tuple(w, h));
        interpolation (str, optional): The interpolation method, its default method is researched 
            by ourself.. Defaults to &#39;huawei&#39;.

    Returns:
        AscendArray: The resized image

    .. note::
        The function resize resizes the image img down to or up to the specified size. Note that the
        initial dst type or size are not taken into account. Instead, the size and type are derived from
        the img, dsize. 

    you may call the function as follows:
    ```python
    # explicitly specify dsize (tuple[int]): Target size (w, h).
    imresize(img, dsize, interpolation)
    ```
    If you want to decimate the image by factor of 2 in each direction, you can call the function this way:
    ```python
    # specify the element w and h of the destination image size.
    imresize(img, (w//2, h//2), interpolation)
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray object, but got {type(img)}.&#34;)

    # valid format is in range [PIXEL_FORMAT_YUV_400 -&gt; PIXEL_FORMAT_BGRA_8888]
    if img.format &lt; 0 or img.format &gt; 17:
        raise ValueError(f&#34;Input image format {img.format} is invalid, only support \
            [PIXEL_FORMAT_YUV_400(0) -&gt; PIXEL_FORMAT_BGRA_8888(17)].&#34;)

    # get the truth h and w of image.
    if img.format in yuv420:
        h, w = (img.shape[0] * 2 // 3, img.shape[1])
    else:
        h, w = img.shape[:2]

    if dsize and not isinstance(dsize, tuple):
        raise TypeError(f&#34;Input dsize expects a tuple object, but got {type(dsize)}.&#34;)

    if dsize and (dsize[0] &gt; 16 * w or dsize[0] &lt; int(1/32 * w)):
        raise ValueError(f&#34;Input dsize[0] out of resize ratio [1/32, 16]&#34;)

    if dsize and (dsize[1] &gt; 16 * h or dsize[1] &lt; int(1/32 * h)):
        raise ValueError(f&#34;Input dsize[1] out of resize ratio [1/32, 16]&#34;)

    if interpolation not in interp_codes.keys():
        raise ValueError(f&#34;Input decode flag {interpolation} is unsupport.&#34;)

    if self._channel_desc is None:
        raise ValueError(f&#34;channel desc is not initialized before imdecode.&#34;)

    # do image aligned and create aligned image to save resized image
    src_img, shape = _align_img(img, func=&#39;resize&#39;)
    dst_img = _create_align_img(dsize[0], dsize[1], format=img.format, func=&#39;resize&#39;)

    # create output image desc and bind it with a output AscendArray object
    # warning: The dst_inst must defined as dst_inst = PicDesc(dst_img), not to be
    #          define as dst_inst = PicDesc(dst_img, dsize), otherwise, the dst image&#39;s
    #          last lines will filled with random colors(value).
    src_inst = PicDesc(src_img, shape)
    dst_inst = PicDesc(dst_img)

    # create resize config
    resize_conf = acl.media.dvpp_create_resize_config()

    # set resize interpolation
    ret = acl.media.dvpp_set_resize_config_interpolation(resize_conf, interp_codes[interpolation])
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to set resize_config_interpolation, return {ret}.&#34;)

    # do image resize
    ret = acl.media.dvpp_vpc_resize_async(self._channel_desc,
                                          src_inst.desc,
                                          dst_inst.desc,
                                          resize_conf,
                                          self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do dvpp_vpc_resize_async, return {ret}.&#34;)

    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to resize image in synchronize_stream, return {ret}.&#34;)

    ret = acl.media.dvpp_destroy_resize_config(resize_conf)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;do dvpp_destroy_resize_config failed, return {ret}.&#34;)

    del (img, src_img, src_inst, dst_inst)
    Log(INFO, &#39;resize image success&#39;)

    return dst_img</code></pre>
</details>
</dd>
<dt id="ascend.Image.imrotate"><code class="name flex">
<span>def <span class="ident">imrotate</span></span>(<span>self, img, angle, center=None, scale=1.0, border_value=0, interpolation='bilinear', auto_bound=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Rotate an image.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image to be rotated.</dd>
<dt><strong><code>angle</code></strong> :&ensp;<code>float</code></dt>
<dd>Rotation angle in degrees, positive values mean clockwise rotation.</dd>
<dt><strong><code>center</code></strong> :&ensp;<code>tuple[float]</code>, optional</dt>
<dd>Center point (w, h) of the rotation in the source
image. If not specified, the center of the image will be used.</dd>
<dt><strong><code>scale</code></strong> :&ensp;<code>float</code>, optional</dt>
<dd>Isotropic scale factor.</dd>
<dt><strong><code>border_value</code></strong> :&ensp;<code>int</code>, optional</dt>
<dd>Border value.</dd>
<dt><strong><code>interpolation</code></strong> :&ensp;<code>str</code>, optional</dt>
<dd>Same as function: <code>resize</code>.</dd>
<dt><strong><code>auto_bound</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Whether to adjust the image size to cover the whole
rotated image.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The rotated image.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L697-L756" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imrotate(self, 
            img,
            angle,
            center=None,
            scale=1.0,
            border_value=0,
            interpolation=&#39;bilinear&#39;,
            auto_bound=False):
    &#34;&#34;&#34;Rotate an image.

    Args:
        img (AscendArray): Image to be rotated.
        angle (float): Rotation angle in degrees, positive values mean clockwise rotation.
        center (tuple[float], optional): Center point (w, h) of the rotation in the source 
            image. If not specified, the center of the image will be used.
        scale (float, optional): Isotropic scale factor.
        border_value (int, optional): Border value.
        interpolation (str, optional): Same as function: `resize`.
        auto_bound (bool, optional): Whether to adjust the image size to cover the whole
            rotated image.

    Returns:
        AscendArray: The rotated image.
    &#34;&#34;&#34;
    try:
        import cv2
        cv2_interp_codes = {
            &#39;nearest&#39;: cv2.INTER_NEAREST,
            &#39;bilinear&#39;: cv2.INTER_LINEAR,
            &#39;bicubic&#39;: cv2.INTER_CUBIC,
            &#39;area&#39;: cv2.INTER_AREA,
            &#39;lanczos&#39;: cv2.INTER_LANCZOS4
        }
    except ImportError:
        Log(ERROR, &#39;import cv2 error while using imrotate, you should install opencv first.&#39;)
        return

    if center is not None and auto_bound:
        raise ValueError(&#39;`auto_bound` conflicts with `center`&#39;)
    h, w = img.shape[:2]
    if center is None:
        center = ((w - 1) * 0.5, (h - 1) * 0.5)
    assert isinstance(center, tuple)

    matrix = cv2.getRotationMatrix2D(center, -angle, scale)
    if auto_bound:
        cos = np.abs(matrix[0, 0])
        sin = np.abs(matrix[0, 1])
        new_w = h * sin + w * cos
        new_h = h * cos + w * sin
        matrix[0, 2] += (new_w - w) * 0.5
        matrix[1, 2] += (new_h - h) * 0.5
        w = int(np.round(new_w))
        h = int(np.round(new_h))
    rotated = cv2.warpAffine(
        img.to_np,
        matrix, (w, h),
        flags=cv2_interp_codes[interpolation],
        borderValue=border_value)
    return AscendArray.clone(rotated)</code></pre>
</details>
</dd>
<dt id="ascend.Image.imwrite"><code class="name flex">
<span>def <span class="ident">imwrite</span></span>(<span>self, img, file_path, params=None, auto_mkdir=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Write image to file.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>img</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>Image array to be written.</dd>
<dt><strong><code>file_path</code></strong> :&ensp;<code>str</code></dt>
<dd>Image file path.</dd>
<dt><strong><code>params</code></strong> :&ensp;<code>None, str</code> or <code>list</code></dt>
<dd>If params=='pillow', save image with PIL. if params is list,
this same as opencv's func: <code>imwrite</code> interface, only work for opencv.</dd>
<dt><strong><code>auto_mkdir</code></strong> :&ensp;<code>bool</code></dt>
<dd>If the parent folder of <code>file_path</code> does not exist,
whether to create it automatically.</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool</code></dt>
<dd>Successful or not.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">Img = ascend.Image(ctx)
Img.imwrite(yuv_org, './saved_img.jpg')  
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/image/geome.py#L1224-L1264" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def imwrite(self, img, file_path, params=None, auto_mkdir=True):
    &#34;&#34;&#34;Write image to file.

    Args:
        img (AscendArray): Image array to be written.
        file_path (str): Image file path.
        params (None, str or list): If params==&#39;pillow&#39;, save image with PIL. if params is list, 
            this same as opencv&#39;s func: `imwrite` interface, only work for opencv.
        auto_mkdir (bool): If the parent folder of `file_path` does not exist,
            whether to create it automatically.

    Returns:
        bool: Successful or not.

    Typical usage example:
    ```python
    Img = ascend.Image(ctx)
    Img.imwrite(yuv_org, &#39;./saved_img.jpg&#39;)  
    ```
    &#34;&#34;&#34;
    if not isinstance(img, AscendArray):
        raise TypeError(f&#34;Input img expects an AscendArray, but got {type(img)}.&#34;)
    
    if auto_mkdir:
        dir_name = osp.abspath(osp.dirname(file_path))
        mkdir_or_exist(dir_name)
    
    if params is None:
        ext = &#39;.png&#39; if file_path.endswith(&#39;.png&#39;) or file_path.endswith(&#39;.PNG&#39;)  else &#39;.jpg&#39;
        file = self.imencode(ext, img)
        with open(file, &#39;w+&#39;) as fw:
            fw.write(file)
    elif params == &#39;pillow&#39;:
        pil_image = Image.fromarray(img.to_np)
        pil_image.save(file_path)
    else:
        try:
            import cv2
            cv2.imwrite(file_path, img.to_np, params)
        except ImportError:
            Log(ERROR, f&#34;import cv2 error while using imwrite save image with params {params}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Matmul"><code class="flex name class">
<span>class <span class="ident">Matmul</span></span>
<span>(</span><span>mat_a, mat_b, mat_c, alpha=1.0, beta=0.0, highprec=True, context=None)</span>
</code></dt>
<dd>
<div class="desc"><p>define a Matmul object, release the function .</p>
<p>Attributes::
context (int): the output image bind with an AscendArray object, image.shape(tupe(h, w, c))
stream (int): The stream resource of this operator
highprec (bool): Precious mode</p>
<h2 id="methods">Methods</h2>
<p>run : do compute matmul
out : return output result</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L37-L186" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Matmul():
    &#34;&#34;&#34; define a Matmul object, release the function .

    Attributes::
        context (int): the output image bind with an AscendArray object, image.shape(tupe(h, w, c))
        stream (int): The stream resource of this operator
        highprec (bool): Precious mode

    Methods:
        run : do compute matmul
        out : return output result
    &#34;&#34;&#34;
    def __init__(self, mat_a, mat_b, mat_c, alpha=1.0, beta=0.0, highprec=True, context=None):
        if context and not isinstance(context, int):
            raise TypeError(f&#34;Input context expects an int, but got {type(context)}.&#34;)

        if not isinstance(mat_a, AscendArray):
            raise TypeError(f&#34;Input mat_a expects an AscendArray, but got {type(mat_a)}.&#34;)

        if not isinstance(mat_b, AscendArray):
            raise TypeError(f&#34;Input mat_a expects an AscendArray, but got {type(mat_b)}.&#34;)

        if not isinstance(mat_c, AscendArray):
            raise TypeError(f&#34;Input mat_a expects an AscendArray, but got {type(mat_c)}.&#34;)

        assert mat_a.format == mat_b.format, f&#34;Input mat_a and mat_b expects same format.&#34;

        # assign self value
        self.context = context
        self.stream = create_stream(context)
        self.highprec = 1 if highprec else 0

        # set op model dir
        ret = acl.op.set_model_dir(&#34;./om&#34;)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;op set model dir failed, return {ret}.&#34;)
        
        # calculate m, n, k and trans alpha and beta to np.ndarray
        self.__pre_compute(mat_a, mat_b, mat_c, alpha, beta)

        # do blas gemm_ex and synchronize stream
        self.run()

        # free input data memory
        self.free_ab()


    def __pre_compute(self, mat_a, mat_b, mat_c, alpha, beta):
        &#34;&#34;&#34; calculate m, n, k and copy alpha/beta to device.
        Args:
            mat_a : (AscendArray) matrix A
            mat_b : (AscendArray) matrix B
            mat_c : (AscendArray) matrix C
            alpha : (float value)
            beta  : (float value)

        Returns:
            None
        &#34;&#34;&#34;
        if mat_a.format in [
            PIXEL_FORMAT_YUV_SEMIPLANAR_420,
            PIXEL_FORMAT_YVU_SEMIPLANAR_420
            ]:
            self.m = mat_a.shape[0] * 2 // 3
            self.n = mat_b.shape[-1]
            self.k = mat_a.shape[1]
        elif mat_a.format in [
            PIXEL_FORMAT_RGB_888,
            PIXEL_FORMAT_BGR_888
            ]:
            self.m = mat_a.shape[0]
            self.n = mat_b.shape[-1]
            self.k = mat_a.shape[1]
        elif mat_a.format == &#39;NCHW&#39;:
            self.m = mat_a.shape[2]
            self.n = mat_b.shape[-1]
            self.k = mat_a.shape[-1]
        elif mat_a.format == &#39;NHWC&#39;:
            self.m = mat_a.shape[1]
            self.n = mat_b.shape[-1]
            self.k = mat_a.shape[2]
        else:
            raise ValueError(f&#34;Input data format not support.&#34;)

        alpha = np.array([alpha]).astype(mat_a.dtype)
        beta  = np.array([beta]).astype(mat_a.dtype)
        self.alpha = AscendArray.clone(alpha)
        self.beta = AscendArray.clone(beta)

    def run(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        a_type = type_map(self.mat_a.dtype)
        b_type = type_map(self.mat_a.dtype)
        c_type = type_map(self.mat_a.dtype)
        # do gemm asyncronize
        ret = acl.blas.gemm_ex(ACL_TRANS_N, ACL_TRANS_N, ACL_TRANS_N, 
                                self.m, self.n, self.k, 
                                self.alpha.ascend_data,
                                self.mat_a.ascend_data, self.k, a_type, 
                                self.mat_b.ascend_data, self.n, b_type, 
                                self.beta.ascend_data,
                                self.mat_c.ascend_data, self.n, c_type, 
                                self.high_prec, 
                                self.stream) 
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do blas gemm_ex, return {ret}.&#34;)

        # do synchronize stream 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in running blas gemm_ex, return {ret}.&#34;)
    
    @property
    def out(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        return self.mat_c

    def free_ab(self):
        &#34;&#34;&#34; free alpha and beta data memory
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        if hasattr(self, &#39;alpha&#39;):
            del self.alpha

        if hasattr(self, &#39;beta&#39;):
            del self.beta

    def __del__(self):
        if hasattr(self, &#39;stream&#39;):
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, f&#34;destroy stream failed, return {ret}.&#34;
        
        # free alpha and beta data memory
        self.free_ab()</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Matmul.out"><code class="name">var <span class="ident">out</span></code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L155-L164" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def out(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    return self.mat_c</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Matmul.free_ab"><code class="name flex">
<span>def <span class="ident">free_ab</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>free alpha and beta data memory</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L166-L178" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def free_ab(self):
    &#34;&#34;&#34; free alpha and beta data memory
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    if hasattr(self, &#39;alpha&#39;):
        del self.alpha

    if hasattr(self, &#39;beta&#39;):
        del self.beta</code></pre>
</details>
</dd>
<dt id="ascend.Matmul.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L126-L153" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    a_type = type_map(self.mat_a.dtype)
    b_type = type_map(self.mat_a.dtype)
    c_type = type_map(self.mat_a.dtype)
    # do gemm asyncronize
    ret = acl.blas.gemm_ex(ACL_TRANS_N, ACL_TRANS_N, ACL_TRANS_N, 
                            self.m, self.n, self.k, 
                            self.alpha.ascend_data,
                            self.mat_a.ascend_data, self.k, a_type, 
                            self.mat_b.ascend_data, self.n, b_type, 
                            self.beta.ascend_data,
                            self.mat_c.ascend_data, self.n, c_type, 
                            self.high_prec, 
                            self.stream) 
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do blas gemm_ex, return {ret}.&#34;)

    # do synchronize stream 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in running blas gemm_ex, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Memory"><code class="flex name class">
<span>class <span class="ident">Memory</span></span>
<span>(</span><span>context, size, flag='DEVICE')</span>
</code></dt>
<dd>
<div class="desc"><p>Define a Memory class to manage memory of device host and dvpp.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>ptr</code></strong> :&ensp;<code>a pointer</code></dt>
<dd>the memmory ptr</dd>
<dt><strong><code>size</code></strong> :&ensp;<code>int value</code></dt>
<dd>the memory size</dd>
<dt><strong><code>flag</code></strong> :&ensp;<code>string</code></dt>
<dd>one of ['DVPP', 'DEVICE', 'HOST']</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">mem = ascend.Memory(context, 32768, flag='DVPP')
print(mem.ptr)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/mem.py#L118-L204" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Memory():
    &#34;&#34;&#34;Define a Memory class to manage memory of device host and dvpp.

    Attributes:
        ptr (a pointer): the memmory ptr
        size (int value): the memory size
        flag (string): one of [&#39;DVPP&#39;, &#39;DEVICE&#39;, &#39;HOST&#39;]

    Typical usage example:
    ```python
    mem = ascend.Memory(context, 32768, flag=&#39;DVPP&#39;)
    print(mem.ptr)
    ```
    &#34;&#34;&#34;
    def __init__(self, context, size, flag=&#34;DEVICE&#34;):
        if not isinstance(size, int):
            raise TypeError(&#39;Memory instance input praram size expects an int value. &#39;
                                f&#39;But received {type(size)}&#39;)
        if size &lt;= 0:
            raise ValueError(&#39;Memory instance input praram size should larger than 0. &#39;
                                f&#39;But received {size}&#39;)

        if flag not in [&#39;DVPP&#39;, &#39;DEVICE&#39;, &#39;HOST&#39;]:
            raise TypeError(&#34;Memory instance input flag expects one of [&#39;DVPP&#39;, &#39;DEVICE&#39;, &#39;HOST&#39;].&#34;)

        # set context
        bind_context(context)

        self.size = size
        self.flag = flag
        self.ptr = malloc(size, flag)

    @classmethod
    def reset(self, ptr, size, value):
        &#34;&#34;&#34;Initial memory with a const value.

        Args:
            ptr (int): Input memory pointer.
            size (int): Input memory size to be reset.
            value (int): The memory value to reset.

        Typical usage example:
        ```python
        pad_val = 0
        ascend.Memory.reset(dst_img.ascend_data, dst_img.nbytes, pad_val)
        ```
        &#34;&#34;&#34;
        if not isinstance(ptr, int):
            raise TypeError(&#34;Input praram &#39;ptr&#39; of func reset expects an int value. &#34;
                                f&#39;But received {type(ptr)}&#39;)
        if not isinstance(size, int):
            raise TypeError(&#34;Input praram &#39;size&#39; of func reset expects an int value. &#34;
                                f&#39;But received {type(size)}&#39;)
        if not isinstance(value, int):
            raise TypeError(&#34;Input praram &#39;value&#39; of func reset expects an int value. &#34;
                                f&#39;But received {type(value)}&#39;)

        ret = acl.rt.memset(ptr, size, value, size)
        if ret != const.ACL_SUCCESS:
            raise ValueError(f&#34;Failed to memset at pointer {ptr}, return value:{ret}.&#34;)
        
    def mem_info(self, attr):
        &#34;&#34;&#34;Get the memory info accoring to attribute att.
        Args:
            attr (int): Input attribute info to get.

        Returns:
            tuple(free, total): The free memory and total memory of device
        
        Typical usage example:
        ```python
        mem = ascend.Memory(context, 32768)
        mem_info = mem.mem_info(0)
        ```
        &#34;&#34;&#34;
        if not isinstance(attr, int):
            raise TypeError(f&#34;Input param expects an int, but got {type(attr)}.&#34;)

        free, total, ret = acl.rt.get_mem_info(attr)
        if ret != const.ACL_SUCCESS:
            raise ValueError(f&#34;Get mem info failed, return {ret}.&#34;)

        return free, total

    def __del__(self):
        if hasattr(self, &#39;ptr&#39;) and self.ptr:
            free(self.ptr, self.flag)</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="ascend.Memory.reset"><code class="name flex">
<span>def <span class="ident">reset</span></span>(<span>ptr, size, value)</span>
</code></dt>
<dd>
<div class="desc"><p>Initial memory with a const value.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>ptr</code></strong> :&ensp;<code>int</code></dt>
<dd>Input memory pointer.</dd>
<dt><strong><code>size</code></strong> :&ensp;<code>int</code></dt>
<dd>Input memory size to be reset.</dd>
<dt><strong><code>value</code></strong> :&ensp;<code>int</code></dt>
<dd>The memory value to reset.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">pad_val = 0
ascend.Memory.reset(dst_img.ascend_data, dst_img.nbytes, pad_val)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/mem.py#L150-L177" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@classmethod
def reset(self, ptr, size, value):
    &#34;&#34;&#34;Initial memory with a const value.

    Args:
        ptr (int): Input memory pointer.
        size (int): Input memory size to be reset.
        value (int): The memory value to reset.

    Typical usage example:
    ```python
    pad_val = 0
    ascend.Memory.reset(dst_img.ascend_data, dst_img.nbytes, pad_val)
    ```
    &#34;&#34;&#34;
    if not isinstance(ptr, int):
        raise TypeError(&#34;Input praram &#39;ptr&#39; of func reset expects an int value. &#34;
                            f&#39;But received {type(ptr)}&#39;)
    if not isinstance(size, int):
        raise TypeError(&#34;Input praram &#39;size&#39; of func reset expects an int value. &#34;
                            f&#39;But received {type(size)}&#39;)
    if not isinstance(value, int):
        raise TypeError(&#34;Input praram &#39;value&#39; of func reset expects an int value. &#34;
                            f&#39;But received {type(value)}&#39;)

    ret = acl.rt.memset(ptr, size, value, size)
    if ret != const.ACL_SUCCESS:
        raise ValueError(f&#34;Failed to memset at pointer {ptr}, return value:{ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Memory.mem_info"><code class="name flex">
<span>def <span class="ident">mem_info</span></span>(<span>self, attr)</span>
</code></dt>
<dd>
<div class="desc"><p>Get the memory info accoring to attribute att.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>attr</code></strong> :&ensp;<code>int</code></dt>
<dd>Input attribute info to get.</dd>
</dl>
<h2 id="returns">Returns</h2>
<p>tuple(free, total): The free memory and total memory of device
Typical usage example:</p>
<pre><code class="language-python">mem = ascend.Memory(context, 32768)
mem_info = mem.mem_info(0)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/resource/mem.py#L179-L200" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def mem_info(self, attr):
    &#34;&#34;&#34;Get the memory info accoring to attribute att.
    Args:
        attr (int): Input attribute info to get.

    Returns:
        tuple(free, total): The free memory and total memory of device
    
    Typical usage example:
    ```python
    mem = ascend.Memory(context, 32768)
    mem_info = mem.mem_info(0)
    ```
    &#34;&#34;&#34;
    if not isinstance(attr, int):
        raise TypeError(f&#34;Input param expects an int, but got {type(attr)}.&#34;)

    free, total, ret = acl.rt.get_mem_info(attr)
    if ret != const.ACL_SUCCESS:
        raise ValueError(f&#34;Get mem info failed, return {ret}.&#34;)

    return free, total</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Permute"><code class="flex name class">
<span>class <span class="ident">Permute</span></span>
<span>(</span><span>input, axes=(0, 2, 3, 1), context=None, stream=None)</span>
</code></dt>
<dd>
<div class="desc"><p>define a Permute operator object to permute the dimensions. </p>
<p>Attributes::
input
: input tensor (AscendArray)
axes
: Permutes the dimensions.
context: input context, optional
stream : input stream, optional</p>
<h2 id="methods">Methods</h2>
<p>run
: do permute
out
: return output result</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L305-L406" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Permute():
    &#34;&#34;&#34; define a Permute operator object to permute the dimensions. 

    Attributes::
        input  : input tensor (AscendArray)
        axes   : Permutes the dimensions.
        context: input context, optional
        stream : input stream, optional

    Methods:
        run    : do permute
        out    : return output result
    &#34;&#34;&#34;
    def __init__(self, input, axes=(0, 2, 3, 1), context=None, stream=None):
        if not isinstance(input, AscendArray):
            raise TypeError(f&#34;Input tensor expects a AscendArray, but got {type(input)}.&#34;)
        
        if not isinstance(axes, (tuple, list)):
            raise TypeError(f&#34;Input axes expects a tuple or list, but got {type(axes)}.&#34;)

        if context and not isinstance(context, int):
            raise TypeError(f&#34;Input context expects an int, but got {type(context)}.&#34;)

        if stream and not isinstance(stream, int):
            raise TypeError(f&#34;Input stream expects an int, but got {type(stream)}.&#34;)

        if tuple(axes) not in [(0, 2, 3, 1), (0, 3, 1, 2)]:
            raise ValueError(f&#34;Input axis only support (0, 2, 3, 1) or (0, 2, 3, 1).&#34;)
            
        # assign self value
        self._axes = axes
        self.context = context
        self.stream = stream if stream else create_stream(context)
        self.created = stream is None

        OpSet()
        self.__pre_set()

        # create output array to save result
        out_shape = tuple([input.shape[i] for i in axes])
        self.output = AscendArray(out_shape, dtype=input.dtype, format=&#39;ND&#39;)
        self.tensor_in = TensorDesc(input)
        self.tensor_out = TensorDesc(self.output)

        # do transpose
        self.run()


    def __pre_set(self):
        &#34;&#34;&#34; set op name and attribute.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        self.op_name = &#34;Permute&#34;
        self.op_attr = acl.op.create_attr()
        ret = acl.op.set_attr_list_int(self.op_attr, &#39;order&#39;, np.array(self._axes, dtype=np.int64))
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Set attr &#39;order&#39; failed, return {ret}.&#34;)


    def run(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        # do op excute
        ret = acl.op.execute(self.op_name,
                             [self.tensor_in.desc],
                             [self.tensor_in.buff],
                             [self.tensor_out.desc],
                             [self.tensor_out.buff],
                             self.op_attr,
                             self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to excute op {self.op_name}, return {ret}.&#34;)

        # do synchronize stream 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in excute op, return {ret}.&#34;)
    
    @property
    def data(self):
        return self.output

    def __del__(self):
        if hasattr(self, &#39;output&#39;):
            del self.output
        if hasattr(self, &#39;tensor_out&#39;):
            del self.tensor_out
        if hasattr(self, &#39;tensor_in&#39;):
            del self.tensor_in

        if hasattr(self, &#39;created&#39;) and self.created:
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, f&#34;destroy stream failed, return {ret}.&#34;</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Permute.data"><code class="name">var <span class="ident">data</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L392-L394" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def data(self):
    return self.output</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Permute.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L368-L390" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    # do op excute
    ret = acl.op.execute(self.op_name,
                         [self.tensor_in.desc],
                         [self.tensor_in.buff],
                         [self.tensor_out.desc],
                         [self.tensor_out.buff],
                         self.op_attr,
                         self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to excute op {self.op_name}, return {ret}.&#34;)

    # do synchronize stream 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in excute op, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Profiling"><code class="flex name class">
<span>class <span class="ident">Profiling</span></span>
<span>(</span><span>context, model_id, mode=1)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a Profiling class to do profiling and finetune model.
It define a decorator running in model infer</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code></dt>
<dd>Context resource</dd>
<dt><strong><code>model_id</code></strong> :&ensp;<code>int</code></dt>
<dd>The model_id that profiling will do.</dd>
</dl>
<h2 id="methods">Methods</h2>
<ul>
<li>profiling(func): do model profiling.</li>
<li>elapse_time(func): do function timling</li>
<li>info_print(sort=False): log infomation of profiling.</li>
</ul>
<p>Typical usage example:</p>
<pre><code class="language-python">prof = ascend.Profiling(ctx, model.model_id)

@prof.elapse_time
@prof.profiling
def run():
    model.run()

run()
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/profiling/profiling.py#L26-L248" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Profiling():
    &#34;&#34;&#34;Define a Profiling class to do profiling and finetune model.
       It define a decorator running in model infer

    Attributes:
        context (int): Context resource
        model_id (int): The model_id that profiling will do.

    Methods:
        - profiling(func): do model profiling.
        - elapse_time(func): do function timling
        - info_print(sort=False): log infomation of profiling.

    Typical usage example:
    ```python
    prof = ascend.Profiling(ctx, model.model_id)

    @prof.elapse_time
    @prof.profiling
    def run():
        model.run()

    run()
    ```
    &#34;&#34;&#34;
    def __init__(self, context, model_id, mode=1):
        if not isinstance(context, int):
            raise TypeError(f&#34;Profiling input context expects an int type, bug got {type(context)}.&#34;)
        
        if not isinstance(model_id, int):
            raise TypeError(f&#34;Profiling input model_id expects an int type, bug got {type(model_id)}.&#34;)

        bind_context(context)

        # create a pipe for communication
        self.r, self.w = os.pipe()
        self._model_id = model_id
        self._thread_id = None
        self._context = context
        self._mode = mode

        # profling data and info
        self.info = []

    def __enter__(self):
        &#34;&#34;&#34;create a subcribe config, and subscribe a thread.

        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        self._subs_conf = acl.prof.create_subscribe_config(1, self._mode , self.w)
        ret = acl.prof.model_subscribe(self._model_id, self._subs_conf)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;configurate model_subscribe failed, return {ret}.&#34;)


    def _get_model_info(self, data, data_len):
        &#34;&#34;&#34; parser profiling data from memory and save to self.info

        Args:
            data    : the operators&#39; information data
            data_len: the operators&#39; information data size

        Returns:
            None
        &#34;&#34;&#34;
        op_number, ret = acl.prof.get_op_num(data, data_len)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;get op num failed, return {ret}.&#34;)

        for i in range(op_number):
            # get model id that operator running
            model_id = acl.prof.get_model_id(data, data_len, i)

            # get type of i-th op
            op_type, ret = acl.prof.get_op_type(data, data_len, i, 65)
            assert ret == ACL_SUCCESS, f&#34;get op type failed, return {ret}.&#34;

            # get name of i-th op
            op_name, ret = acl.prof.get_op_name(data, data_len, i, 275)
            assert ret == ACL_SUCCESS, f&#34;get op type failed, return {ret}.&#34;

            # get running start time of i-th op
            op_start = acl.prof.get_op_start(data, data_len, i)

            # get running end time of i-th op
            op_end = acl.prof.get_op_end(data, data_len, i)

            # get runnning duration of i-th op
            op_duration = acl.prof.get_op_duration(data, data_len, i)

            # save profiling result
            self.info.append([model_id, op_name, op_type, op_start, op_end, op_duration])

    def info_print(self, sort=False):
        &#34;&#34;&#34;Print profiling info to terminal

        Args:
            sort (bool, optional): Whether sort the profiling result or not. Defaults to False.

        Typical usage example:
        ```python
        prof.info_print(sort=True)
        ```     
        &#34;&#34;&#34;
        items = [&#39;id&#39;, &#39;op_name&#39;, &#39;op_type&#39;, &#39;time_start&#39;, &#39;time_end&#39;, &#39;time_elapse&#39;]
        table = PrettyTable(items)

        for item in self.info:
            table.add_row(item)
        
        percent = np.array([e[-1] for e in self.info])
        percent = np.around(100 * percent / percent.sum(), decimals=2)
        table.add_column(&#39;percent(%)&#39;, percent)
        
        print(table.get_string(sortby=&#39;time_elapse&#39; if sort else None, reversesort=True))

    def _read_data(self, args):
        &#34;&#34;&#34; read profiling data to pipe and save on memory.

        Args:
            args : function input parameter
 
        Returns:
            None
        &#34;&#34;&#34;
        fd, ctx = args

        # bind context resource
        bind_context(ctx)
        
        buffer_size, ret = acl.prof.get_op_desc_size()
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;get op desc of size failed, return {ret}.&#34;)

        # caculate memory size for save op info
        data_len = buffer_size * 10

        # read profiling data from pipe, the data size maybe lower than buffer_size*N
        while True:
            data = os.read(fd, data_len)
            if len(data) == 0:
                break

            # malloc numpy data memory to save profiling data
            np_data = np.array(data)
            np_data_ptr = acl.util.numpy_to_ptr(np_data)

            # parser profiling data 
            size = np_data.itemsize * np_data.size
            self._get_model_info(np_data_ptr, size)

    def profiling(self, func):
        &#34;&#34;&#34;Start profiling thread and do profiling.

        Args:
            func (obj): the function to do profiling

        Returns:
            wrapped_function
        &#34;&#34;&#34;
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            print(func.__name__ + &#34; was called, and start profiling.&#34;)

            # start profiling
            with self:
                self._thread_id, ret = acl.util.start_thread(self._read_data, [self.r, self._context])
                if ret != ACL_SUCCESS:
                    raise ValueError(f&#34;start tread {self._thread_id} failed, return {ret}.&#34;)
                
                return func(*args, **kwargs)

        return wrapped_function

    def elapse_time(self, func):
        &#34;&#34;&#34;Print function excute time.

        Args:
            func (obj): The runing function.

        Returns:
            wrapped_function
        &#34;&#34;&#34;        
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            print(func.__name__ + &#34; was called, and start time.&#34;)
            
            start_time = time.time()
            res = func(*args, **kwargs)
            use_time = time.time() - start_time

            print(f&#34;{func.__name__} elapse time:{use_time}&#34;)
            return res
        return wrapped_function


    def __exit__(self, exc_type, exc_value, traceback):
        &#34;&#34;&#34; unsubscribe thread and destroy subscribe config.

        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        if hasattr(self, &#39;_model_id&#39;):
            ret = acl.prof.model_un_subscribe(self._model_id)
            assert ret == ACL_SUCCESS, f&#34;unsubscribe profiling thread failed, return {ret}.&#34;

        if hasattr(self, &#39;_thread_id&#39;):
            ret = acl.util.stop_thread(self._thread_id)
            assert ret == ACL_SUCCESS, f&#34;stop thread {self._thread_id} failed, return {ret}.&#34;

        # close pipe
        os.close(self.r)

        ret = acl.prof.destroy_subscribe_config(self._subs_conf)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;destroy subscribe config of profiling failed, return {ret}.&#34;)</code></pre>
</details>
<h3>Methods</h3>
<dl>
<dt id="ascend.Profiling.elapse_time"><code class="name flex">
<span>def <span class="ident">elapse_time</span></span>(<span>self, func)</span>
</code></dt>
<dd>
<div class="desc"><p>Print function excute time.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>func</code></strong> :&ensp;<code>obj</code></dt>
<dd>The runing function.</dd>
</dl>
<h2 id="returns">Returns</h2>
<p>wrapped_function</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/profiling/profiling.py#L204-L223" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def elapse_time(self, func):
    &#34;&#34;&#34;Print function excute time.

    Args:
        func (obj): The runing function.

    Returns:
        wrapped_function
    &#34;&#34;&#34;        
    @wraps(func)
    def wrapped_function(*args, **kwargs):
        print(func.__name__ + &#34; was called, and start time.&#34;)
        
        start_time = time.time()
        res = func(*args, **kwargs)
        use_time = time.time() - start_time

        print(f&#34;{func.__name__} elapse time:{use_time}&#34;)
        return res
    return wrapped_function</code></pre>
</details>
</dd>
<dt id="ascend.Profiling.info_print"><code class="name flex">
<span>def <span class="ident">info_print</span></span>(<span>self, sort=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Print profiling info to terminal</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>sort</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Whether sort the profiling result or not. Defaults to False.</dd>
</dl>
<p>Typical usage example:</p>
<pre><code class="language-python">prof.info_print(sort=True)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/profiling/profiling.py#L123-L144" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def info_print(self, sort=False):
    &#34;&#34;&#34;Print profiling info to terminal

    Args:
        sort (bool, optional): Whether sort the profiling result or not. Defaults to False.

    Typical usage example:
    ```python
    prof.info_print(sort=True)
    ```     
    &#34;&#34;&#34;
    items = [&#39;id&#39;, &#39;op_name&#39;, &#39;op_type&#39;, &#39;time_start&#39;, &#39;time_end&#39;, &#39;time_elapse&#39;]
    table = PrettyTable(items)

    for item in self.info:
        table.add_row(item)
    
    percent = np.array([e[-1] for e in self.info])
    percent = np.around(100 * percent / percent.sum(), decimals=2)
    table.add_column(&#39;percent(%)&#39;, percent)
    
    print(table.get_string(sortby=&#39;time_elapse&#39; if sort else None, reversesort=True))</code></pre>
</details>
</dd>
<dt id="ascend.Profiling.profiling"><code class="name flex">
<span>def <span class="ident">profiling</span></span>(<span>self, func)</span>
</code></dt>
<dd>
<div class="desc"><p>Start profiling thread and do profiling.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>func</code></strong> :&ensp;<code>obj</code></dt>
<dd>the function to do profiling</dd>
</dl>
<h2 id="returns">Returns</h2>
<p>wrapped_function</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/profiling/profiling.py#L181-L202" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def profiling(self, func):
    &#34;&#34;&#34;Start profiling thread and do profiling.

    Args:
        func (obj): the function to do profiling

    Returns:
        wrapped_function
    &#34;&#34;&#34;
    @wraps(func)
    def wrapped_function(*args, **kwargs):
        print(func.__name__ + &#34; was called, and start profiling.&#34;)

        # start profiling
        with self:
            self._thread_id, ret = acl.util.start_thread(self._read_data, [self.r, self._context])
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;start tread {self._thread_id} failed, return {ret}.&#34;)
            
            return func(*args, **kwargs)

    return wrapped_function</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Transpose"><code class="flex name class">
<span>class <span class="ident">Transpose</span></span>
<span>(</span><span>input, perm=[0, 1, 2, 3], context=None, stream=None)</span>
</code></dt>
<dd>
<div class="desc"><p>define a Transpose operator object to release Transpose. Permutes the dimensions according to perm.
The returned tensor's dimension i will correspond to the input dimension perm[i] </p>
<h2 id="args">Args</h2>
<dl>
<dt>input
: input tensor (AscendArray)</dt>
<dt>perm
: Permutes the dimensions.</dt>
<dt><strong><code>context</code></strong></dt>
<dd>input context, optional</dd>
</dl>
<p>stream : input stream, optional</p>
<h2 id="methods">Methods</h2>
<p>run
: do permute
out
: return output result</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L207-L300" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Transpose():
    &#34;&#34;&#34; define a Transpose operator object to release Transpose. Permutes the dimensions according to perm. 
        The returned tensor&#39;s dimension i will correspond to the input dimension perm[i] 

    Args:
        input  : input tensor (AscendArray)
        perm   : Permutes the dimensions.
        context: input context, optional
        stream : input stream, optional

    Methods:
        run    : do permute
        out    : return output result
    &#34;&#34;&#34;
    def __init__(self, input, perm=[0, 1, 2, 3], context=None, stream=None):
        if not isinstance(input, AscendArray):
            raise TypeError(f&#34;Input tensor expects a AscendArray, but got {type(input)}.&#34;)

        if context and not isinstance(context, int):
            raise TypeError(f&#34;Input context expects an int, but got {type(context)}.&#34;)

        if stream and not isinstance(stream, int):
            raise TypeError(f&#34;Input stream expects an int, but got {type(stream)}.&#34;)

        # assign self value
        self.context = context
        self.stream = stream if stream else create_stream(context)
        self.created = stream is None

        OpSet()
        self.__pre_set()

        # create output array to save result
        _perm = AscendArray.clone(np.array(perm, dtype=&#39;int32&#39;))
        self.output = AscendArray(input.shape, dtype=input.dtype, format=&#39;ND&#39;)
        self.tensor_in1 = TensorDesc(input)
        self.tensor_in2 = TensorDesc(_perm)
        self.tensor_out = TensorDesc(self.output)

        # do transpose
        self.run()


    def __pre_set(self):
        &#34;&#34;&#34; set op name and attribute.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        self.op_name = &#34;Transpose&#34;
        self.op_attr = acl.op.create_attr()


    def run(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        # do op excute
        ret = acl.op.execute(self.op_name,
                             [self.tensor_in1.desc, self.tensor_in2.desc],
                             [self.tensor_in1.buff, self.tensor_in2.buff],
                             [self.tensor_out.desc],
                             [self.tensor_out.buff],
                             self.op_attr,
                             self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to excute op {self.op_name}, return {ret}.&#34;)

        # do synchronize stream 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in excute op, return {ret}.&#34;)
    
    @property
    def data(self):
        return self.output

    def __del__(self):
        if hasattr(self, &#39;output&#39;):
            del self.output
        if hasattr(self, &#39;tensor_out&#39;):
            del self.tensor_out
        if hasattr(self, &#39;tensor_in&#39;):
            del self.tensor_in

        if self.created:
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, f&#34;destroy stream failed, return {ret}.&#34;</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Transpose.data"><code class="name">var <span class="ident">data</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L286-L288" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def data(self):
    return self.output</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Transpose.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/op.py#L262-L284" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    # do op excute
    ret = acl.op.execute(self.op_name,
                         [self.tensor_in1.desc, self.tensor_in2.desc],
                         [self.tensor_in1.buff, self.tensor_in2.buff],
                         [self.tensor_out.desc],
                         [self.tensor_out.buff],
                         self.op_attr,
                         self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to excute op {self.op_name}, return {ret}.&#34;)

    # do synchronize stream 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in excute op, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Vdec"><code class="flex name class">
<span>class <span class="ident">Vdec</span></span>
<span>(</span><span>context, channel=0, en_type=0, pix_fmt=1, timeout=50)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L29-L422" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Vdec():
    def __init__(self, 
                context, 
                channel=0, 
                en_type=0, 
                pix_fmt=PIXEL_FORMAT_YUV_SEMIPLANAR_420, 
                timeout=50):
        self.class_name = self.__class__.__name__
        self.__check_para(context, channel, en_type)
        self._vdec_exit = True

        # video channel parameter
        self.context     = context
        self._channel_id = channel
        self._en_type    = en_type
        self._format     = pix_fmt

        # video decoder queue, to save decoded image. Default queue size is 25.
        self.image = Queue(maxsize=25)
        self.qsize = 25

        self._bind_thread = self.__init_thread(timeout=timeout)
        self.channel_desc = self.__vdec_create_channel()
        self._frame_conf = self.__frame_config()

    def __check_para(self, context, channel, en_type):
        &#34;&#34;&#34; check input parameters of instance Vdec.
        Args:
            context : the device context resource.
            string  : input stream.
            channel : the channel id of Vdec.
            en_type : the encode type of stream.

        Returns:
            None.
        &#34;&#34;&#34;
        # bind context
        bind_context(context)

        if channel &lt; 0 or channel &gt; 31:
            raise ValueError(f&#34;Configurated channel_id is out of range [0 31].&#34;)

        if en_type not in [H265_MAIN_LEVEL, H264_BASELINE_LEVEL, H264_MAIN_LEVEL, H264_HIGH_LEVEL]:
            raise ValueError(f&#34;Configurated en_type is invalid.&#34;)

    def __init_thread(self, timeout=100):
        &#34;&#34;&#34; initial a thread to watch the callback.
        Args:
            timeout: 

        Returns:
            None.
        &#34;&#34;&#34;
        cb_thread_id, ret = acl.util.start_thread(self.__thread_func, [timeout])
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Vdec initial acl thread failed, return {ret}.&#34;)
        
        return cb_thread_id

    def __thread_func(self, args_list):
        # bind context resource
        bind_context(self.context)

        timeout = args_list[0]
        while self._vdec_exit:
            acl.rt.process_report(timeout)

        Log(INFO, &#39;vdec_thread_func out&#39;)

    def __callback(self, input_stream_desc, output_pic_desc, user_data):
        &#34;&#34;&#34;inner callback function of video decoder.
        Args:
            input_stream_desc, output_pic_desc, user_data

        Returns:
            None.
        &#34;&#34;&#34;
        # step 1: release input stream desc and free input memory
        if input_stream_desc:
            ret = acl.media.dvpp_destroy_stream_desc(input_stream_desc)
            if ret != ACL_SUCCESS:
                Log(WARNING, f&#39;destroy input_stream_desc failed, return {ret}.&#39;)

        # step 2: save the decode image and release desc
        if output_pic_desc:
            if self.image.qsize() == self.qsize - 1:
                Log(WARNING, f&#39;buffer queue {self.image.queue()} is almost full.&#39;)

            ret = acl.media.dvpp_get_pic_desc_ret_code(output_pic_desc)
            if ret != ACL_SUCCESS:
                Log(WARNING, f&#39;image decode error, return {ret}.&#39;)
            else:
                size = acl.media.dvpp_get_pic_desc_size(output_pic_desc)
                buffer = acl.media.dvpp_get_pic_desc_data(output_pic_desc)
                align_w = acl.media.dvpp_get_pic_desc_width_stride(output_pic_desc)

                frame_id = user_data[0]
                yuv_image = AscendArray((align_w,), np.dtype(&#39;uint8&#39;), size=size, buffer=buffer,\
                                         format=self._format, flag=&#39;DEVICE&#39;)

                self.image.put((frame_id, yuv_image.reshape(yuv_image.shape[::-1])), timeout=30)
                self._channel_id = user_data[1]

            ret = acl.media.dvpp_destroy_pic_desc(output_pic_desc)
            if ret != 0:
                Log(WARNING, f&#39;destroy pic desc failed, return {ret}.&#39;)
        
        Log(INFO, f&#39;frame:{user_data[0]} vdec decoding frame success.&#39;)          
                

    def __vdec_create_channel(self):
        &#34;&#34;&#34; create a vdec channel, and bind it with a thread and other info.
        Args:
            None

        Returns:
            channel_desc : the created channel desc resource
        &#34;&#34;&#34;
        channel_desc = acl.media.vdec_create_channel_desc()

        ret = acl.media.vdec_set_channel_desc_channel_id(channel_desc, self._channel_id)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc channel id, return {ret}.&#34;
        
        ret = acl.media.vdec_set_channel_desc_thread_id(channel_desc, self._bind_thread)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc thread id, return {ret}.&#34;

        ret = acl.media.vdec_set_channel_desc_callback(channel_desc, self.__callback)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc call back, return {ret}.&#34;

        ret = acl.media.vdec_set_channel_desc_entype(channel_desc, self._en_type)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel en_type, return {ret}.&#34;

        ret = acl.media.vdec_set_channel_desc_out_pic_format(channel_desc, self._format)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc format, return {ret}.&#34;

        ret = acl.media.vdec_create_channel(channel_desc)
        assert ret == ACL_SUCCESS, f&#34;Failed to create channel desc, return {ret}.&#34;

        Log(INFO, &#39;Vdec init success&#39;)
        return channel_desc

    def __frame_config(self):
        &#34;&#34;&#34;create a frame config.
        Args:
            None

        Returns:
            frame_conf.
        &#34;&#34;&#34;
        frame_conf = acl.media.vdec_create_frame_config()

        Log(INFO, &#39;frame config success in vdec init.&#39;)
        return frame_conf 

    def __stream_desc(self, frame):
        &#34;&#34;&#34; create a stream desc and bind to input frame data pointer and size info.
        Args:
            frame : input frame packet
        Returns:
            stream_desc: the created stream desc.
        &#34;&#34;&#34;
        stream_desc = acl.media.dvpp_create_stream_desc()

        # if the last frame, send an Eos frame to vdec
        if frame.is_last:
            Log(INFO, &#39;Start to send EOS frame.&#39;)
            ret = acl.media.dvpp_set_stream_desc_eos(stream_desc, 1)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to set EOS to input stream desc, return {ret}.&#34;)
            return stream_desc
    
        ret = acl.media.dvpp_set_stream_desc_data(stream_desc, frame.data)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set stream desc data, return {ret}.&#34;)

        ret = acl.media.dvpp_set_stream_desc_size(stream_desc, frame.size)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set stream desc size, return {ret}.&#34;)
        return  stream_desc

    def __pic_desc(self, width, height):
        &#34;&#34;&#34; create a output image desc and bind memory and other info.
        Args:
            height  : output image&#39;s width
            width   : output image&#39;s height
        Returns:
            pic_desc: the created image desc.
        &#34;&#34;&#34;
        aligned_w = aligned(width, aligned=&#39;w&#39;)
        aligned_h = aligned(height, aligned=&#39;h&#39;)

        buffer_size = calc_size(aligned_w, aligned_h, self._format)
        buffer = malloc(buffer_size, flag=&#39;DVPP&#39;)
                
        # create picture desc resource
        pic_desc = acl.media.dvpp_create_pic_desc()

        ret = acl.media.dvpp_set_pic_desc_data(pic_desc, buffer)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set pic desc data, return {ret}.&#34;)

        ret = acl.media.dvpp_set_pic_desc_size(pic_desc, buffer_size)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set pic desc size, return {ret}.&#34;)

        ret = acl.media.dvpp_set_pic_desc_format(pic_desc, self._format)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set pic desc format, return {ret}.&#34;)

        return pic_desc

    def process(self, frame):
        &#34;&#34;&#34;Read one packet frame from caputure in host and send to dvpp.
        Args:
            frame : a frame packet with data and frame info

        Returns:
            None.
        &#34;&#34;&#34;
        if not isinstance(frame, Frame):
            raise TypeError(f&#34;Input frame expects Frame instance, but got {type(frame)}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel_desc must be created before using in process.&#34;)

        if not hasattr(self, &#39;_frame_conf&#39;):
            raise ValueError(f&#34;vdec _frame_conf must be created before using in process.&#34;)
        # configurate input stream
        stream_desc = self.__stream_desc(frame)

        # configure output picture
        pic_desc = self.__pic_desc(frame.width, frame.height)

        user_data = (frame.frame_id, self._channel_id)
        # send one frame to vdec
        ret = acl.media.vdec_send_frame(self.channel_desc,
                                        stream_desc,
                                        pic_desc,
                                        self._frame_conf,
                                        user_data)
        if ret != ACL_SUCCESS:
            Log(WARNING, &#39;vdec send frame failed.&#39;)
        
    def finish(self):
        &#34;&#34;&#34; finish bind thread working. 

        .. warning:: 
            This function should be called after sending last eos-frame.
        &#34;&#34;&#34;
        self._vdec_exit = False
            
        ret = acl.util.stop_thread(self._bind_thread)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to stop bind thread {self._bind_thread}, return {ret}.&#34;)


    @property
    def queue_size(self):
        return self.image.qsize()

    @queue_size.setter
    def queue_size(self, maxsize):
        if not self.image.empty():
            raise ValueError(f&#34;Original queue should be empty before configuring.&#34;)
        self.qsize = maxsize
        self.image = Queue(maxsize=maxsize)

    @property
    def channel_id(self):
        return self._channel_id

    @channel_id.setter
    def channel_id(self, channel_id):
        if not isinstance(channel_id, int):
            raise TypeError(f&#34;Configurate channel_id expects an int, but got {type(channel_id)}.&#34;)
        
        if channel_id &lt; 0 or channel_id &gt; 31:
            raise ValueError(f&#34;Configurate channel_id is out of range [0 31].&#34;)
        
        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set channel_id.&#34;)

        ret = acl.media.vdec_set_channel_desc_channel_id(self.channel_desc, channel_id)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel id, return {ret}.&#34;
        self._channel_id = channel_id

    @property
    def encoder_type(self):
        return self._en_type

    @encoder_type.setter
    def encoder_type(self, encoder_type):
        if not isinstance(encoder_type, int):
            raise TypeError(f&#34;Configurate encoder_type expects an int, but got {type(encoder_type)}.&#34;)

        if encoder_type &lt; 0 or encoder_type &gt; 4:
            raise ValueError(f&#34;Configurate encoder_type is out of range [0 3] \
                    (0:H265_MAIN_LEVEL, 1:H264_BASELINE_LEVEL, 2:H264_MAIN_LEVEL, 3:H264_HIGH_LEVEL).&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set encoder_type.&#34;)

        ret = acl.media.vdec_set_channel_desc_entype(self.channel_desc, encoder_type)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel en_type, return {ret}.&#34;
        self._en_type = encoder_type

    @property
    def pic_format(self):
        return self._format

    @pic_format.setter
    def pic_format(self, pic_format):
        if not isinstance(pic_format, int):
            raise TypeError(f&#34;Configurate encoder_type expects an int, but got {type(pic_format)}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set pic_format.&#34;)

        ret = acl.media.vdec_set_channel_desc_out_pic_format(self.channel_desc, pic_format)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel pic_format, return {ret}.&#34;
        self._format = pic_format

    @property
    def ref_num(self):
        ref_frame_num = acl.media.vdec_get_channel_desc_ref_frame_num(self.channel_desc)
        return ref_frame_num

    @property
    def out_mode(self):
        out_mode, ret = acl.media.vdec_get_channel_desc_out_mode(self.channel_desc)
        assert ret == ACL_SUCCESS, f&#34;Failed to get channel out_mode, return {ret}.&#34;
        return out_mode

    @out_mode.setter
    def out_mode(self, out_mode):
        if not isinstance(out_mode, int):
            raise TypeError(f&#34;Configure out_mode expects an int, but got {type(out_mode)}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set out_mode.&#34;)

        ret = acl.media.vdec_set_channel_desc_out_mode(self.channel_desc, out_mode)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;vdec set channel out_mode failed, return {ret}.&#34;)
        

    @property
    def bit_depth(self):
        bit_depth = acl.media.vdec_get_channel_desc_bit_depth(self.channel_desc)
        return bit_depth
    
    @bit_depth.setter
    def bit_depth(self, bit_depth):
        if not isinstance(bit_depth, int):
            raise TypeError(f&#34;input bit_depth expects an int, but got {type(bit_depth)}.&#34;)

        if bit_depth != 0 and bit_depth != 1:
            raise TypeError(f&#34;input bit_depth expects 0 or 1, but got {bit_depth}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set out_mode.&#34;)

        ret = acl.media.vdec_set_channel_desc_bit_depth(self.channel_desc, bit_depth)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;vdec set bit_depth failed, return {ret}.&#34;)

    def __del__(self):
        # bind context to release
        bind_context(self.context)
        
        if hasattr(self, &#39;channel_desc&#39;):
            ret = acl.media.vdec_destroy_channel(self.channel_desc)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to destroy vdec channel, return {ret}.&#34;)
            
            ret = acl.media.vdec_destroy_channel_desc(self.channel_desc)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to destroy vdec channel desc, return {ret}.&#34;)
        
        if hasattr(self, &#39;_frame_conf&#39;):
            ret = acl.media.vdec_destroy_frame_config(self._frame_conf)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to destroy frame config, return {ret}.&#34;)
        
        self._vdec_exit = False
        
        if hasattr(self, &#39;_bind_thread&#39;):
            ret = acl.util.stop_thread(self._bind_thread)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to stop bind thread {self._bind_thread}, return {ret}.&#34;)
        
        while not self.image.empty():
            data = self.image.get()
            del data</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Vdec.bit_depth"><code class="name">var <span class="ident">bit_depth</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L375-L378" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def bit_depth(self):
    bit_depth = acl.media.vdec_get_channel_desc_bit_depth(self.channel_desc)
    return bit_depth</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.channel_id"><code class="name">var <span class="ident">channel_id</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L296-L298" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def channel_id(self):
    return self._channel_id</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.encoder_type"><code class="name">var <span class="ident">encoder_type</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L315-L317" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def encoder_type(self):
    return self._en_type</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.out_mode"><code class="name">var <span class="ident">out_mode</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L356-L360" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def out_mode(self):
    out_mode, ret = acl.media.vdec_get_channel_desc_out_mode(self.channel_desc)
    assert ret == ACL_SUCCESS, f&#34;Failed to get channel out_mode, return {ret}.&#34;
    return out_mode</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.pic_format"><code class="name">var <span class="ident">pic_format</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L335-L337" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def pic_format(self):
    return self._format</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.queue_size"><code class="name">var <span class="ident">queue_size</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L285-L287" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def queue_size(self):
    return self.image.qsize()</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.ref_num"><code class="name">var <span class="ident">ref_num</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L351-L354" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def ref_num(self):
    ref_frame_num = acl.media.vdec_get_channel_desc_ref_frame_num(self.channel_desc)
    return ref_frame_num</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Vdec.finish"><code class="name flex">
<span>def <span class="ident">finish</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>finish bind thread working. </p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>This function should be called after sending last eos-frame.</p>
</div></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L272-L282" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def finish(self):
    &#34;&#34;&#34; finish bind thread working. 

    .. warning:: 
        This function should be called after sending last eos-frame.
    &#34;&#34;&#34;
    self._vdec_exit = False
        
    ret = acl.util.stop_thread(self._bind_thread)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to stop bind thread {self._bind_thread}, return {ret}.&#34;)</code></pre>
</details>
</dd>
<dt id="ascend.Vdec.process"><code class="name flex">
<span>def <span class="ident">process</span></span>(<span>self, frame)</span>
</code></dt>
<dd>
<div class="desc"><p>Read one packet frame from caputure in host and send to dvpp.</p>
<h2 id="args">Args</h2>
<p>frame : a frame packet with data and frame info</p>
<h2 id="returns">Returns</h2>
<p>None.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/vdec.py#L240-L270" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def process(self, frame):
    &#34;&#34;&#34;Read one packet frame from caputure in host and send to dvpp.
    Args:
        frame : a frame packet with data and frame info

    Returns:
        None.
    &#34;&#34;&#34;
    if not isinstance(frame, Frame):
        raise TypeError(f&#34;Input frame expects Frame instance, but got {type(frame)}.&#34;)

    if not hasattr(self, &#39;channel_desc&#39;):
        raise ValueError(f&#34;vdec channel_desc must be created before using in process.&#34;)

    if not hasattr(self, &#39;_frame_conf&#39;):
        raise ValueError(f&#34;vdec _frame_conf must be created before using in process.&#34;)
    # configurate input stream
    stream_desc = self.__stream_desc(frame)

    # configure output picture
    pic_desc = self.__pic_desc(frame.width, frame.height)

    user_data = (frame.frame_id, self._channel_id)
    # send one frame to vdec
    ret = acl.media.vdec_send_frame(self.channel_desc,
                                    stream_desc,
                                    pic_desc,
                                    self._frame_conf,
                                    user_data)
    if ret != ACL_SUCCESS:
        Log(WARNING, &#39;vdec send frame failed.&#39;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Venc"><code class="flex name class">
<span>class <span class="ident">Venc</span></span>
<span>(</span><span>context, stream_dir, width, height, en_type=0, frame_interval=25, pix_fmt=1, timeout=50)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a Venc class to encode the frame using dvpp.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code></dt>
<dd>context resource of this module working on</dd>
<dt><strong><code>stream_dir</code></strong> :&ensp;<code>str</code></dt>
<dd>a string or Path to save the encoded stream</dd>
<dt><strong><code>width</code></strong> :&ensp;<code>int</code></dt>
<dd>the encoding frame's width</dd>
<dt><strong><code>height</code></strong> :&ensp;<code>int</code></dt>
<dd>the encoding frame's height</dd>
<dt><strong><code>en_type</code></strong> :&ensp;<code>int</code></dt>
<dd>encode type of dvpp</dd>
<dt><strong><code>frame_itval</code></strong> :&ensp;<code>int</code></dt>
<dd>key frame interval, and the defaut value is 25</dd>
<dt><strong><code>pix_fmt</code></strong> :&ensp;<code>int</code></dt>
<dd>the frame's pixel format, only support yuv420 NV12/NV21</dd>
<dt><strong><code>timeout</code></strong> :&ensp;<code>int</code></dt>
<dd>the encoding thread time out of dvpp </dd>
<dt><strong><code>rc_mode</code></strong> :&ensp;<code>int</code></dt>
<dd>set/get frame number of video stream</dd>
<dt><strong><code>fps</code></strong> :&ensp;<code>int</code></dt>
<dd>set/get frame per second of encoding stream </dd>
<dt><strong><code>bit_rate</code></strong> :&ensp;<code>int</code></dt>
<dd>set/get bit rate</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L66-L474" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Venc():
    &#34;&#34;&#34;Define a Venc class to encode the frame using dvpp.

    Attributes:
        context (int): context resource of this module working on
        stream_dir (str): a string or Path to save the encoded stream
        width (int): the encoding frame&#39;s width
        height (int): the encoding frame&#39;s height
        en_type (int): encode type of dvpp
        frame_itval (int): key frame interval, and the defaut value is 25
        pix_fmt (int): the frame&#39;s pixel format, only support yuv420 NV12/NV21
        timeout (int): the encoding thread time out of dvpp 
        rc_mode (int): set/get frame number of video stream
        fps (int): set/get frame per second of encoding stream 
        bit_rate (int): set/get bit rate
 
    &#34;&#34;&#34;
    def __init__(self, 
                context, 
                stream_dir,
                width,
                height,
                en_type=0, 
                frame_interval = 25,
                pix_fmt=PIXEL_FORMAT_YUV_SEMIPLANAR_420, 
                timeout=50):
        self.class_name = self.__class__.__name__
        self._venc_exit = True

        # video parameter
        self.context     = context
        self.stream_dir  = stream_dir
        self._width      = width
        self._height     = height
        self._en_type    = en_type
        self._format     = pix_fmt
        self._frame_itval= frame_interval
        self.__check_para()

        self._bind_thread = self.__init_thread(timeout=timeout)
        self.channel_desc = self.__venc_create_channel()
        self._en_frame = EncFrame()

    def __check_para(self):
        &#34;&#34;&#34; check input parameters of instance Vdec.
        Args:
            None

        Returns:
            None.
        &#34;&#34;&#34;
        # bind context
        bind_context(self.context)

        if not is_filepath(self.stream_dir):
            raise ValueError(f&#34;Input stream_dir:{self.stream_dir} is not exist.&#34;)

        if self._width &lt; 128 or self._width &gt; 1920:
            raise ValueError(f&#34;Input width only support [0, 1920].&#34;)

        if self._height &lt; 128 or self._height &gt; 1920:
            raise ValueError(f&#34;Input height only support [0, 1080].&#34;)

        if self._en_type not in [H265_MAIN_LEVEL, H264_BASELINE_LEVEL, H264_MAIN_LEVEL, H264_HIGH_LEVEL]:
            raise ValueError(f&#34;Configurated en_type is invalid.&#34;)

        if self._format not in [PIXEL_FORMAT_YUV_SEMIPLANAR_420, PIXEL_FORMAT_YVU_SEMIPLANAR_420]:
            raise ValueError(f&#34;Input pix_fmt only support yuv420 and yvu420.&#34;)

        if self._frame_itval &lt; 1 or self._frame_itval &gt; 65536:
            raise ValueError(f&#34;Input frame_interval only support [1, 65536].&#34;)

    def __init_thread(self, timeout=100):
        &#34;&#34;&#34; initial a thread to watch the callback.
        Args:
            timeout: 

        Returns:
            None.
        &#34;&#34;&#34;
        cb_thread_id, ret = acl.util.start_thread(self.__thread_func, [self.context, timeout])
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Venc initial acl thread failed, return {ret}.&#34;)
        
        return cb_thread_id

    def __thread_func(self, args_list):
        context = args_list[0]
        timeout = args_list[1]

        # bind context
        bind_context(context)
        
        while self._venc_exit:
            acl.rt.process_report(timeout)

        Log(INFO, &#39;vdec_thread_func out&#39;)


    def __callback(self, input_pic_desc, output_stream_desc, user_data):
        &#34;&#34;&#34;inner callback function of video encoder.
        Args:
            input_pic_desc, output_tream_desc, user_data

        Returns:
            None.
        &#34;&#34;&#34;
        # step 1: release input stream desc and free input memory
        if output_stream_desc == 0:
            Log(INFO, &#39;output_stream_desc is null in callback.&#39;)
            return

        stream_data = acl.media.dvpp_get_stream_desc_data(output_stream_desc)
        if stream_data is None:
            Log(INFO, &#39;stream_data is None in func dvpp_get_stream_desc_data.&#39;)
            return

        ret = acl.media.dvpp_get_stream_desc_ret_code(output_stream_desc)
        if ret != ACL_SUCCESS:
            Log(INFO, f&#39;dvpp_get_stream_desc_ret_code in callback is {ret}.&#39;)
            return 

        stream_size = acl.media.dvpp_get_stream_desc_size(output_stream_desc)
        
        # step 2: numpy array to save encode data
        enc_data = np.zeros(stream_size, dtype=np.byte)
        enc_dptr = acl.util.numpy_to_ptr(enc_data)

        # copy device data to host
        memcpy_d2h(enc_dptr, stream_data, stream_size)

        # step 3: write encode stream
        with open(self.stream_dir, &#39;ab&#39;) as f:
            f.write(enc_data)
        
    def __venc_create_channel(self):
        &#34;&#34;&#34; create a venc channel, and band it with a thread and other info.
        Args:
            None

        Returns:
            channel_desc : the created channel desc resource
        &#34;&#34;&#34;
        channel_desc = acl.media.venc_create_channel_desc()

        ret = acl.media.venc_set_channel_desc_thread_id(channel_desc, self._bind_thread)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc thread id, return {ret}.&#34;

        ret = acl.media.venc_set_channel_desc_callback(channel_desc, self.__callback)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc call back, return {ret}.&#34;

        ret = acl.media.venc_set_channel_desc_entype(channel_desc, self._en_type)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel en_type, return {ret}.&#34;

        ret = acl.media.venc_set_channel_desc_pic_format(channel_desc, self._format)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc format, return {ret}.&#34;

        ret = acl.media.venc_set_channel_desc_key_frame_interval(channel_desc, self._frame_itval)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc frame interval, return {ret}.&#34;

        ret = acl.media.venc_set_channel_desc_pic_height(channel_desc, self._height)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc width, return {ret}.&#34;

        ret = acl.media.venc_set_channel_desc_pic_width(channel_desc, self._width)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel desc height, return {ret}.&#34;

        ret = acl.media.venc_create_channel(channel_desc)
        assert ret == ACL_SUCCESS, f&#34;Failed to create channel desc, return {ret}.&#34;

        Log(INFO, &#39;__venc_create_channel init success&#39;)
        return channel_desc



    def __pic_desc(self, frame):
        &#34;&#34;&#34; create a input image desc and bind memory and other info.
        Args:
            frame : input frame
        Returns:
            pic_desc: the created picture desc.
        &#34;&#34;&#34;
        pic_desc = acl.media.dvpp_create_pic_desc()

        # if the last frame, send an Eos frame to venc
        if frame.is_last:
            return self._en_frame.eos()

        ret = acl.media.dvpp_set_pic_desc_data(pic_desc, frame.data)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set stream desc data, return {ret}.&#34;)

        ret = acl.media.dvpp_set_pic_desc_size(pic_desc, frame.size)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to set stream desc size, return {ret}.&#34;)
        return  pic_desc

    def finish(self):
        &#34;&#34;&#34; create a eos stream desc and set it to vdec.
        
        .. warning::
                this function should be called after processing all valid frame.
        Args:
            None
        Returns:
            pic_desc: the created picture desc.
        &#34;&#34;&#34;
        # step 1: set finish configure
        stream_desc = acl.media.dvpp_create_stream_desc()

        # stream_desc set function
        ret = acl.media.dvpp_set_stream_desc_format(stream_desc, self._en_type)
        assert ret == ACL_SUCCESS, f&#34;set stream desc format failed, return {ret}.&#34; 

        ret = acl.media.dvpp_set_stream_desc_timestamp(stream_desc, int(time.time()))
        assert ret == ACL_SUCCESS, f&#34;set stream desc timestamp failed, return {ret}.&#34;

        ret = acl.media.dvpp_set_stream_desc_ret_code(stream_desc, 1)
        assert ret == ACL_SUCCESS, f&#34;set stream desc ret code failed, return {ret}.&#34;

        ret = acl.media.dvpp_set_stream_desc_eos(stream_desc, 1)
        assert ret == ACL_SUCCESS, f&#34;set stream desc eos failed, return {ret}.&#34;

        ret = acl.media.dvpp_destroy_stream_desc(stream_desc)
        assert ret == ACL_SUCCESS, f&#34;destroy stream desc failed, return {ret}.&#34;

        # step 2: stop thread
        self._venc_exit = False
        
        ret = acl.util.stop_thread(self._bind_thread)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to stop band thread {self._bind_thread}, return {ret}.&#34;)


    def process(self, frame):
        &#34;&#34;&#34;Assemble one frame and send to video encoder
        Args:
            frame : a frame with data and frame info

        Returns:
            None.
        &#34;&#34;&#34;
        if not isinstance(frame, Frame):
            raise TypeError(f&#34;Input frame expects Frame instance, but got {type(frame)}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel_desc must be created before using in process.&#34;)

        # configurate input picture description
        pic_desc = self.__pic_desc(frame)

        # send one frame to venc
        ret = acl.media.venc_send_frame(self.channel_desc,
                                        pic_desc,
                                        0,
                                        self._en_frame.frame_conf,
                                        None)
        if ret != ACL_SUCCESS:
            Log(WARNING, &#39;vdec send frame failed.&#39;)

        Log(INFO, &#34;venc send frame success.&#34;)

    @property
    def width(self):
        width = acl.media.venc_get_channel_desc_pic_width(self.channel_desc)
        return width

    @width.setter
    def width(self, width):
        if width &lt; 128 or width &gt; 1920:
            raise ValueError(f&#34;Input width expects in range [128, 1920], but got {width}.&#34;)

        ret = acl.media.venc_set_channel_desc_pic_width(self.channel_desc, width)
        assert ret == ACL_SUCCESS, f&#34;set channel desc pic width failed, return {ret}.&#34;
        self._width = width

    @property
    def height(self):
        height = acl.media.venc_get_channel_desc_pic_height(self.channel_desc)
        return height

    @height.setter
    def height(self, height):
        if height &lt; 128 or height &gt; 1920:
            raise ValueError(f&#34;Input height expects in range [128, 1920], but got {height}.&#34;)

        ret = acl.media.venc_set_channel_desc_pic_height(self.channel_desc, height)
        assert ret == ACL_SUCCESS, f&#34;set channel desc pic height failed, return {ret}.&#34;
        self._height = height

    @property
    def encoder_type(self):
        return self._en_type

    @encoder_type.setter
    def encoder_type(self, encoder_type):
        if not isinstance(encoder_type, int):
            raise TypeError(f&#34;Configurate encoder_type expects an int, but got {type(encoder_type)}.&#34;)

        if encoder_type &lt; 0 or encoder_type &gt; 4:
            raise ValueError(f&#34;Configurate encoder_type is out of range [0 3] \
                    (0:H265_MAIN_LEVEL, 1:H264_BASELINE_LEVEL, 2:H264_MAIN_LEVEL, 3:H264_HIGH_LEVEL).&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set encoder_type.&#34;)

        ret = acl.media.venc_set_channel_desc_entype(self.channel_desc, encoder_type)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel en_type, return {ret}.&#34;
        self._en_type = encoder_type

    @property
    def pic_format(self):
        return self._format

    @pic_format.setter
    def pic_format(self, pic_format):
        if not isinstance(pic_format, int):
            raise TypeError(f&#34;Configurate encoder_type expects an int, but got {type(pic_format)}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set pic_format.&#34;)

        ret = acl.media.venc_set_channel_desc_pic_format(self.channel_desc, pic_format)
        assert ret == ACL_SUCCESS, f&#34;Failed to set channel pic_format, return {ret}.&#34;
        self._format = pic_format

    @property
    def frame_itval(self):
        return self._frame_itval

    @frame_itval.setter
    def frame_itval(self, frame_itval):
        if not isinstance(frame_itval, int):
            raise TypeError(f&#34;Configure frame_itval expects an int, but got {type(frame_itval)}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;vdec channel desc must be created before set frame_itval.&#34;)

        ret = acl.media.venc_set_channel_desc_key_frame_interval(self.channel_desc, frame_itval)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;vdec set channel frame_itval failed, return {ret}.&#34;)
        

    @property
    def fps(self):
        fps = acl.media.venc_get_channel_desc_src_rate(self.channel_desc)
        return fps
    
    @fps.setter
    def fps(self, fps):
        if not isinstance(fps, int):
            raise TypeError(f&#34;input fps expects an int, but got {type(fps)}.&#34;)

        if fps &lt; 1 or fps &gt; 120:
            raise TypeError(f&#34;input fps expects in [1, 120], but got {fps}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;venc channel desc must be created before set fps.&#34;)

        ret = acl.media.venc_set_channel_desc_src_rate(self.channel_desc, fps)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;venc set fps failed, return {ret}.&#34;)

    @property
    def rc_mode(self):
        rc_mode = acl.media.venc_get_channel_desc_rc_mode(self.channel_desc)
        return rc_mode

    @rc_mode.setter
    def rc_mode(self, rc_mode):
        if rc_mode &lt; 0 or rc_mode &gt; 2:
            raise TypeError(f&#34;input rc_mode expects in [0, 2], but got {rc_mode}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;venc channel desc must be created before set rc_mode.&#34;)

        ret = acl.media.venc_set_channel_desc_rc_mode(self.channel_desc, rc_mode)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;venc set rc_mode failed, return {ret}.&#34;)

    @property
    def bit_rate(self):
        bit_rate = acl.media.venc_get_channel_desc_max_bit_rate(self.channel_desc)
        return bit_rate

    @bit_rate.setter
    def bit_rate(self, bit_rate):
        if bit_rate &lt; 10 or bit_rate &gt; 30000:
            raise TypeError(f&#34;input bit_rate expects in [10, 30000], but got {bit_rate}.&#34;)

        if not hasattr(self, &#39;channel_desc&#39;):
            raise ValueError(f&#34;venc channel desc must be created before set bit_rate.&#34;)

        ret = acl.media.venc_set_channel_desc_max_bit_rate(self.channel_desc, bit_rate)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;venc set bit_rate failed, return {ret}.&#34;)


    def __del__(self):
        # bind context to release
        bind_context(self.context)
        
        if hasattr(self, &#39;channel_desc&#39;):
            ret = acl.media.vdec_destroy_channel(self.channel_desc)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to destroy vdec channel, return {ret}.&#34;)
            
            ret = acl.media.vdec_destroy_channel_desc(self.channel_desc)
            if ret != ACL_SUCCESS:
                raise ValueError(f&#34;Failed to destroy vdec channel desc, return {ret}.&#34;)        </code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Venc.bit_rate"><code class="name">var <span class="ident">bit_rate</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L445-L448" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def bit_rate(self):
    bit_rate = acl.media.venc_get_channel_desc_max_bit_rate(self.channel_desc)
    return bit_rate</code></pre>
</details>
</dd>
<dt id="ascend.Venc.encoder_type"><code class="name">var <span class="ident">encoder_type</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L355-L357" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def encoder_type(self):
    return self._en_type</code></pre>
</details>
</dd>
<dt id="ascend.Venc.fps"><code class="name">var <span class="ident">fps</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L408-L411" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def fps(self):
    fps = acl.media.venc_get_channel_desc_src_rate(self.channel_desc)
    return fps</code></pre>
</details>
</dd>
<dt id="ascend.Venc.frame_itval"><code class="name">var <span class="ident">frame_itval</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L391-L393" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def frame_itval(self):
    return self._frame_itval</code></pre>
</details>
</dd>
<dt id="ascend.Venc.height"><code class="name">var <span class="ident">height</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L341-L344" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def height(self):
    height = acl.media.venc_get_channel_desc_pic_height(self.channel_desc)
    return height</code></pre>
</details>
</dd>
<dt id="ascend.Venc.pic_format"><code class="name">var <span class="ident">pic_format</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L375-L377" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def pic_format(self):
    return self._format</code></pre>
</details>
</dd>
<dt id="ascend.Venc.rc_mode"><code class="name">var <span class="ident">rc_mode</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L428-L431" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def rc_mode(self):
    rc_mode = acl.media.venc_get_channel_desc_rc_mode(self.channel_desc)
    return rc_mode</code></pre>
</details>
</dd>
<dt id="ascend.Venc.width"><code class="name">var <span class="ident">width</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L327-L330" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def width(self):
    width = acl.media.venc_get_channel_desc_pic_width(self.channel_desc)
    return width</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Venc.finish"><code class="name flex">
<span>def <span class="ident">finish</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>create a eos stream desc and set it to vdec.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>this function should be called after processing all valid frame.</p>
</div>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>pic_desc</code></dt>
<dd>the created picture desc.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L262-L296" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def finish(self):
    &#34;&#34;&#34; create a eos stream desc and set it to vdec.
    
    .. warning::
            this function should be called after processing all valid frame.
    Args:
        None
    Returns:
        pic_desc: the created picture desc.
    &#34;&#34;&#34;
    # step 1: set finish configure
    stream_desc = acl.media.dvpp_create_stream_desc()

    # stream_desc set function
    ret = acl.media.dvpp_set_stream_desc_format(stream_desc, self._en_type)
    assert ret == ACL_SUCCESS, f&#34;set stream desc format failed, return {ret}.&#34; 

    ret = acl.media.dvpp_set_stream_desc_timestamp(stream_desc, int(time.time()))
    assert ret == ACL_SUCCESS, f&#34;set stream desc timestamp failed, return {ret}.&#34;

    ret = acl.media.dvpp_set_stream_desc_ret_code(stream_desc, 1)
    assert ret == ACL_SUCCESS, f&#34;set stream desc ret code failed, return {ret}.&#34;

    ret = acl.media.dvpp_set_stream_desc_eos(stream_desc, 1)
    assert ret == ACL_SUCCESS, f&#34;set stream desc eos failed, return {ret}.&#34;

    ret = acl.media.dvpp_destroy_stream_desc(stream_desc)
    assert ret == ACL_SUCCESS, f&#34;destroy stream desc failed, return {ret}.&#34;

    # step 2: stop thread
    self._venc_exit = False
    
    ret = acl.util.stop_thread(self._bind_thread)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to stop band thread {self._bind_thread}, return {ret}.&#34;)</code></pre>
</details>
</dd>
<dt id="ascend.Venc.process"><code class="name flex">
<span>def <span class="ident">process</span></span>(<span>self, frame)</span>
</code></dt>
<dd>
<div class="desc"><p>Assemble one frame and send to video encoder</p>
<h2 id="args">Args</h2>
<p>frame : a frame with data and frame info</p>
<h2 id="returns">Returns</h2>
<p>None.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/venc.py#L299-L325" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def process(self, frame):
    &#34;&#34;&#34;Assemble one frame and send to video encoder
    Args:
        frame : a frame with data and frame info

    Returns:
        None.
    &#34;&#34;&#34;
    if not isinstance(frame, Frame):
        raise TypeError(f&#34;Input frame expects Frame instance, but got {type(frame)}.&#34;)

    if not hasattr(self, &#39;channel_desc&#39;):
        raise ValueError(f&#34;vdec channel_desc must be created before using in process.&#34;)

    # configurate input picture description
    pic_desc = self.__pic_desc(frame)

    # send one frame to venc
    ret = acl.media.venc_send_frame(self.channel_desc,
                                    pic_desc,
                                    0,
                                    self._en_frame.frame_conf,
                                    None)
    if ret != ACL_SUCCESS:
        Log(WARNING, &#39;vdec send frame failed.&#39;)

    Log(INFO, &#34;venc send frame success.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.VideoCapture"><code class="flex name class">
<span>class <span class="ident">VideoCapture</span></span>
<span>(</span><span>context, stream_path, channel=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a VideoCaputure class to get the stream and parser packet. It also include method to push
packets to ascend dvpp video decoder, and the decoder only support annex-b h264 video format or
rtsp ip camera. </p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Input an IP video stream for video capturing, and stream_path expect an absolute path for video dir.</p>
</div>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>context</code></strong> :&ensp;<code>int</code></dt>
<dd>context resource video capture working on</dd>
<dt><strong><code>container</code></strong> :&ensp;<code>av.Container obj</code></dt>
<dd>The pyav container object.</dd>
<dt><strong><code>stream</code></strong> :&ensp;<code>container.streams obj</code></dt>
<dd>The pyav Container streams object.</dd>
<dt><strong><code>packets</code></strong> :&ensp;<code>av.Packet obj</code></dt>
<dd>The pyav Packet object.</dd>
<dt><strong><code>decoder</code></strong> :&ensp;<code><a title="ascend.Vdec" href="#ascend.Vdec">Vdec</a> obj</code></dt>
<dd>The ascend DVPP decoder object.</dd>
<dt><strong><code>width</code></strong> :&ensp;<code>int</code></dt>
<dd>frame's width</dd>
<dt><strong><code>height</code></strong> :&ensp;<code>int</code></dt>
<dd>frame's height</dd>
<dt><strong><code>coded_height</code></strong> :&ensp;<code>int</code></dt>
<dd>video coded height</dd>
<dt><strong><code>codel_width</code></strong> :&ensp;<code>int</code></dt>
<dd>video coded width</dd>
<dt><strong><code>display_aspect_ratio</code></strong> :&ensp;<code>Fraction obj</code></dt>
<dd>get the video stream display aspect ratio.</dd>
<dt><strong><code>format</code></strong> :&ensp;<code>av.VideoFormat obj</code></dt>
<dd>video stream format.</dd>
<dt><strong><code>framerate</code></strong> :&ensp;<code>float</code></dt>
<dd>video stream framerate</dd>
<dt><strong><code>fps</code></strong> :&ensp;<code>float</code></dt>
<dd>video stream framerate, same to framerate</dd>
<dt><strong><code>has_b_frames</code></strong> :&ensp;<code>bool</code></dt>
<dd>bool value, indicate stream has b frames</dd>
<dt><strong><code>pix_fmt</code></strong> :&ensp;<code>int</code></dt>
<dd>the decoded frame's pixel format</dd>
<dt><strong><code>frames</code></strong> :&ensp;<code>int</code></dt>
<dd>frame number of video stream</dd>
</dl>
<h2 id="methods">Methods</h2>
<ul>
<li>skip_frame : Signal that we only want to look at frames, only work in ffmpeg</li>
<li>is_open
: Returns true if video capturing has been initialized already</li>
<li>read
: Grabs, decodes and returns the next video frame</li>
<li>set
: Sets a property in the VideoCapture</li>
<li>get
: Returns the specified VideoCapture property</li>
<li>release
: Closes and release video capture's resource</li>
</ul></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L38-L394" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class VideoCapture():
    &#34;&#34;&#34;Define a VideoCaputure class to get the stream and parser packet. It also include method to push 
       packets to ascend dvpp video decoder, and the decoder only support annex-b h264 video format or
       rtsp ip camera. 
    
    .. warning::
       Input an IP video stream for video capturing, and stream_path expect an absolute path for video dir. 

    Attributes:
        context (int): context resource video capture working on
        container (av.Container obj): The pyav container object.
        stream (container.streams obj): The pyav Container streams object.
        packets (av.Packet obj): The pyav Packet object.
        decoder (Vdec obj): The ascend DVPP decoder object.
        width (int): frame&#39;s width
        height (int): frame&#39;s height
        coded_height (int): video coded height
        codel_width (int): video coded width
        display_aspect_ratio (Fraction obj): get the video stream display aspect ratio.
        format (av.VideoFormat obj): video stream format.
        framerate (float): video stream framerate
        fps (float): video stream framerate, same to framerate
        has_b_frames (bool): bool value, indicate stream has b frames
        pix_fmt (int): the decoded frame&#39;s pixel format
        frames (int): frame number of video stream


    Methods:
        - skip_frame : Signal that we only want to look at frames, only work in ffmpeg
        - is_open    : Returns true if video capturing has been initialized already
        - read       : Grabs, decodes and returns the next video frame
        - set        : Sets a property in the VideoCapture
        - get        : Returns the specified VideoCapture property
        - release    : Closes and release video capture&#39;s resource

    &#34;&#34;&#34;
    def __init__(self, context, stream_path, channel=None):
        if not isinstance(stream_path, str):
            raise TypeError(f&#34;Input stream_path expects an string in initial VideoCapture, \
                 but got {type(stream_path)}.&#34;)

        if not isinstance(context, int):
            raise TypeError(f&#34;VideoCaputre input context expects an int type, bug got {type(context)}.&#34;)

        self.context = context
        self._status = Status.IDLE

        # open video container
        self.container = av.open(av.datasets.curated(stream_path))

        # only use video stream
        self.stream = self.container.streams.video[0]
        
        # check video format is support or not, and get en_type of video stream.
        en_type = self.__check_stream_format(self.stream.codec_context)
        
        # push stream.
        self.stream.thread_type = &#39;AUTO&#39;
        self.packets = self.container.demux()

        # set context
        bind_context(context)

        pix_fmt = pix_fmt_map.get(self.stream.pix_fmt, PIXEL_FORMAT_YUV_SEMIPLANAR_420)
        chan_id = channel if channel else self.stream.id
        self.decoder = Vdec(context, en_type=en_type, pix_fmt=pix_fmt, channel=chan_id)

        # set initial working status
        self._frame = 0
        self._status = Status.READY

    def __check_stream_format(self, codec_context):
        &#34;&#34;&#34; check the video stream format is Annex-b or not, and Annex-b format h264 extradata is start
            with 0x000001 or 0x00000001
        Args:
            stream : input stream

        Returns:
            None
        &#34;&#34;&#34;
        extradata = np.frombuffer(codec_context.extradata, np.ubyte)
        if (extradata[:3] == [0, 0, 1]).all():
            profile_id = extradata[4]
        elif (extradata[:4] == [0, 0, 0, 1]).all():
            profile_id = extradata[5]
        else:
            raise ValueError(f&#34;Input stream {stream} is not annex-b h264.&#34;)

        if codec_context.name not in [&#39;h264&#39;, &#39;h265&#39;]:
            raise ValueError(f&#34;unsupport this video stream codec type {codec_context.name}.&#34;)

        try:
            en_type = en_type_map[profile_id]
        except KeyError:
            raise ValueError(f&#34;Input stream format is not one of {en_type_map}.&#34;)

        return en_type


    @property
    def width(self):
        return self.stream.width

    @property
    def height(self):
        return self.stream.height

    @property
    def coded_height(self):
        return self.stream.coded_height

    @property
    def coded_width(self):
        return self.stream.coded_width

    @property
    def display_aspect_ratio(self):
        &#34;&#34;&#34;
        .. note:: 
            Get the video stream display aspect ratio, and it returns an fraction object 
            like Fraction(16, 9).
        &#34;&#34;&#34;
        return self.stream.display_aspect_ratio

    @property
    def format(self):
        &#34;&#34;&#34;
        .. note:: 
            Get the video stream format info like &lt;av.VideoFormat yuv420p, 3840x2160&gt;. It 
            return an av.VideoFormat object.
        &#34;&#34;&#34;
        return self.stream.format

    @property
    def framerate(self):
        return float(self.stream.framerate)

    @property
    def fps(self):
        return self.framerate

    @property
    def has_b_frames(self):
        return self.stream.has_b_frames

    @property
    def pix_fmt(self):
        return self.stream.pix_fmt

    @property
    def frames(self):
        return self.stream.frames

    def skip_frame(self, skip_type):
        &#34;&#34;&#34;Signal that we only want to look at frames, only work in ffmpeg.
        Args:
            skip_type (int): A class of av.codec.context.SkipType

        ```python
        -------------------------------------------------------------------------------
        SkipType Name | Flag Value | Meaning in FFmpeg                                 
        --------------+------------+---------------------------------------------------
        NONE          | 0x-10      | Discard nothing                                   
        DEFAULT       | 0x0        | Discard useless packets like 0 size packets in AVI
        NONREF        | 0x8        | Discard all non reference                         
        BIDIR         | 0x10       | Discard all bidirectional frames                  
        NONINTRA      | 0x18       | Discard all non intra frames                      
        NONKEY        | 0x20       | Discard all frames except keyframes               
        ALL           | 0x30       | Discard all                                       
        -------------------------------------------------------------------------------
        ```
        &#34;&#34;&#34;
        if not isinstance(skip_type, str):
            raise TypeError(f&#34;Input skip_type expect a string, but got {type(skip_type)}.&#34;)

        if skip_type in [&#39;NONE&#39;, &#39;DEFAULT&#39;, &#39;NONREF&#39;, &#39;BIDIR&#39;, &#39;NONINTRA&#39;, &#39;NONKEY&#39;, &#39;ALL&#39;]:
            self.stream.codec_context.skip_frame = skip_type
        else:
            Log(WARNING, &#39;skip_frame set value failed in Video Capture.&#39;)


    def is_open(self):
        &#34;&#34;&#34;Open the video capture and ready to decode.

        ```python
        The decode working on 5 status: IDLE, READY/START, RUN, END
        =================================================================================
        Status IDLE  | the idle status of decode, and the resource is uninitial, and
                     | nothing can be used in instance. 
        ---------------------------------------------------------------------------------
        Status READY | class VideoCapture and Vdec is initialized, and waiting for start. 
        ---------------------------------------------------------------------------------
        Status START | this status start to open vdec and the dequeue is null, so it will
                     | push packet until dequeue has decoded-image data. 
        ---------------------------------------------------------------------------------
        Status RUN   | run video decoder and pull stream packet until packet is null. 
        ---------------------------------------------------------------------------------
        Status END   | end of push packet to the vdec, and pop image data until the  
                     | dequeue is null. 
        =================================================================================
        ```
        Args:
            None

        Returns:
            bool : True for VideoCapture is ready or False.
        &#34;&#34;&#34;
        if self._status == Status.START or self._status == Status.READY:
            # get one packet data
            packet = next(self.packets)

            # if packet is null, jump to status IDLE
            if packet.buffer_size &lt;= 0:
                self._status == Status.IDLE
                return False

            # construct a frame
            self._frame = self._frame + 1
            shape = (self.stream.width, self.stream.height)
            frame = Frame(packet, shape, frame_id=self._frame, context=self.context)

            # do video decode
            self.decoder.process(frame)

            # if dequeue has image data, it jump to status RUN
            if not self.decoder.image.empty():
                self._status = Status.RUN
            return True

        elif self._status == Status.RUN:
            # get one packet data
            packet = next(self.packets)
            
            # if packet is null, send eos frame and jump to status IDLE
            shape = (self.stream.width, self.stream.height)
            if packet.buffer_size &lt;= 0:
                # send eos frame
                frame = Frame(packet, shape, is_last=True, context=self.context)

                # after send eos, it jump to status END
                self._status = Status.END
            else:
                self._frame = self._frame + 1
                frame = Frame(packet, shape, frame_id=self._frame, context=self.context)

            # do video decode
            self.decoder.process(frame)
            return True

        elif self._status == Status.END:
            if self.decoder.image.empty():
                self.decoder.finish()
                self._status = Status.IDLE
                return False

            return True
        else:
            self._status = Status.IDLE
            return False


    def read(self, print_status=True):     
        &#34;&#34;&#34;Read one frame from caputure in device. If we cann&#39;t get the data in the timeout, 
            it will be raise an timeout error.
        Args:
            print_status (bool, optional): Get the queue status for True

        Returns:
            [AscendArray]: Get a decoded frame.
        &#34;&#34;&#34;
        if self._status != Status.IDLE and not self.decoder.image.empty():
            if print_status:
                Log(INFO, f&#34;qsize = {self.decoder.image.qsize()}.&#34;)
                print(f&#34;qsize = {self.decoder.image.qsize()}&#34;)
            frame_id, image = self.decoder.image.get(timeout=30)
            
            return image, frame_id
        else:
            Log(WARNING, &#39;read image failed in Video Capture.&#39;)
            return (None, None)

    def set(self, attr, value):
        &#34;&#34;&#34;set(attr, value) -&gt; retval
            Sets a property in the VideoCapture
        Args:
            attr (str): Property from VideoCapture Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
            value (int): Value of the property

        Returns:
            bool : `True` if the property is supported by the backend used by the VideoCapture instance.
        &#34;&#34;&#34;
        if self._status == Status.READY:
            if attr == &#39;qsize&#39;: 
                self.decoder.queue_size = value
            elif attr == &#39;channel_id&#39;: 
                self.decoder.channel_id = value
            elif attr == &#39;ref_num&#39;: 
                self.decoder.ref_num = value
            elif attr == &#39;enc_type&#39;: 
                self.decoder.encoder_type = value
            elif attr == &#39;pix_fmt&#39;: 
                self.decoder.pic_format = value
            elif attr == &#39;bit_depth&#39;: 
                self.decoder.bit_depth = value
            elif attr == &#39;out_mode&#39;: 
                self.decoder.out_mode = value
            else:
                Log(ERROR, f&#39;attr {attr} is not support in VideoCapture.&#39;)
                return False
            return True
        else:
            Log(ERROR, f&#39;Set attr {attr} in status {self._status}.&#39;)
            raise ValueError(f&#34;Set attr {attr} in status {self._status}.&#34;)

    def get(self, attr):   
        &#34;&#34;&#34; get(attr) -&gt; retval
            Returns the specified VideoCapture property
        Args:
            attr (str): Property from VideoCapture Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
            
        Returns:
            [Value]: Value for the specified property. Value 0 is returned when querying a 
                property that is not supported by the backend used by the VideoCapture instance.
        &#34;&#34;&#34;
        if not isinstance(attr, str):
            raise TypeError(f&#34;Input attr expects a string, but got {type(attr)}.&#34;)
        
        attr_dict = {
            &#39;width&#39;       : self.stream.width,
            &#39;height&#39;      : self.stream.height,
            &#39;frame_height&#39;: self.stream.coded_height,
            &#39;frame_width&#39; : self.stream.coded_width,
            &#39;aspect_ratio&#39;: self.stream.display_aspect_ratio,
            &#39;fps&#39;         : self.framerate,
            &#39;format&#39;      : self.stream.format,
            &#39;pix_fmt&#39;     : self.stream.pix_fmt, 
            &#39;frames&#39;      : self.stream.frames
        }

        try:
            return attr_dict[attr]
        except KeyError:
            return 0

    def release(self):
        &#34;&#34;&#34;Closes video file or capturing device and release resource.
        &#34;&#34;&#34;
        if hasattr(self, &#39;container&#39;):
            self.container.close()

        if hasattr(self, &#39;decoder&#39;):
            del self.decoder
        
        self._status = False

    def __del__(self):
        self.release()</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.VideoCapture.coded_height"><code class="name">var <span class="ident">coded_height</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L145-L147" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def coded_height(self):
    return self.stream.coded_height</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.coded_width"><code class="name">var <span class="ident">coded_width</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L149-L151" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def coded_width(self):
    return self.stream.coded_width</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.display_aspect_ratio"><code class="name">var <span class="ident">display_aspect_ratio</span></code></dt>
<dd>
<div class="desc"><div class="admonition note">
<p class="admonition-title">Note</p>
<p>Get the video stream display aspect ratio, and it returns an fraction object
like Fraction(16, 9).</p>
</div></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L153-L160" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def display_aspect_ratio(self):
    &#34;&#34;&#34;
    .. note:: 
        Get the video stream display aspect ratio, and it returns an fraction object 
        like Fraction(16, 9).
    &#34;&#34;&#34;
    return self.stream.display_aspect_ratio</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.format"><code class="name">var <span class="ident">format</span></code></dt>
<dd>
<div class="desc"><div class="admonition note">
<p class="admonition-title">Note</p>
<p>Get the video stream format info like <av.VideoFormat yuv420p, 3840x2160>. It
return an av.VideoFormat object.</p>
</div></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L162-L169" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def format(self):
    &#34;&#34;&#34;
    .. note:: 
        Get the video stream format info like &lt;av.VideoFormat yuv420p, 3840x2160&gt;. It 
        return an av.VideoFormat object.
    &#34;&#34;&#34;
    return self.stream.format</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.fps"><code class="name">var <span class="ident">fps</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L175-L177" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def fps(self):
    return self.framerate</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.framerate"><code class="name">var <span class="ident">framerate</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L171-L173" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def framerate(self):
    return float(self.stream.framerate)</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.frames"><code class="name">var <span class="ident">frames</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L187-L189" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def frames(self):
    return self.stream.frames</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.has_b_frames"><code class="name">var <span class="ident">has_b_frames</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L179-L181" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def has_b_frames(self):
    return self.stream.has_b_frames</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.height"><code class="name">var <span class="ident">height</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L141-L143" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def height(self):
    return self.stream.height</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.pix_fmt"><code class="name">var <span class="ident">pix_fmt</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L183-L185" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def pix_fmt(self):
    return self.stream.pix_fmt</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.width"><code class="name">var <span class="ident">width</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L137-L139" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def width(self):
    return self.stream.width</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.VideoCapture.get"><code class="name flex">
<span>def <span class="ident">get</span></span>(<span>self, attr)</span>
</code></dt>
<dd>
<div class="desc"><p>get(attr) -&gt; retval
Returns the specified VideoCapture property</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>attr</code></strong> :&ensp;<code>str</code></dt>
<dd>Property from VideoCapture Properties (eg. 'width', 'fps', &hellip;)</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[Value]</code></dt>
<dd>Value for the specified property. Value 0 is returned when querying a
property that is not supported by the backend used by the VideoCapture instance.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L352-L380" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def get(self, attr):   
    &#34;&#34;&#34; get(attr) -&gt; retval
        Returns the specified VideoCapture property
    Args:
        attr (str): Property from VideoCapture Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
        
    Returns:
        [Value]: Value for the specified property. Value 0 is returned when querying a 
            property that is not supported by the backend used by the VideoCapture instance.
    &#34;&#34;&#34;
    if not isinstance(attr, str):
        raise TypeError(f&#34;Input attr expects a string, but got {type(attr)}.&#34;)
    
    attr_dict = {
        &#39;width&#39;       : self.stream.width,
        &#39;height&#39;      : self.stream.height,
        &#39;frame_height&#39;: self.stream.coded_height,
        &#39;frame_width&#39; : self.stream.coded_width,
        &#39;aspect_ratio&#39;: self.stream.display_aspect_ratio,
        &#39;fps&#39;         : self.framerate,
        &#39;format&#39;      : self.stream.format,
        &#39;pix_fmt&#39;     : self.stream.pix_fmt, 
        &#39;frames&#39;      : self.stream.frames
    }

    try:
        return attr_dict[attr]
    except KeyError:
        return 0</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.is_open"><code class="name flex">
<span>def <span class="ident">is_open</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Open the video capture and ready to decode.</p>
<pre><code class="language-python">The decode working on 5 status: IDLE, READY/START, RUN, END
=================================================================================
Status IDLE  | the idle status of decode, and the resource is uninitial, and
             | nothing can be used in instance. 
---------------------------------------------------------------------------------
Status READY | class VideoCapture and Vdec is initialized, and waiting for start. 
---------------------------------------------------------------------------------
Status START | this status start to open vdec and the dequeue is null, so it will
             | push packet until dequeue has decoded-image data. 
---------------------------------------------------------------------------------
Status RUN   | run video decoder and pull stream packet until packet is null. 
---------------------------------------------------------------------------------
Status END   | end of push packet to the vdec, and pop image data until the  
             | dequeue is null. 
=================================================================================
</code></pre>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool </code></dt>
<dd>True for VideoCapture is ready or False.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L219-L296" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def is_open(self):
    &#34;&#34;&#34;Open the video capture and ready to decode.

    ```python
    The decode working on 5 status: IDLE, READY/START, RUN, END
    =================================================================================
    Status IDLE  | the idle status of decode, and the resource is uninitial, and
                 | nothing can be used in instance. 
    ---------------------------------------------------------------------------------
    Status READY | class VideoCapture and Vdec is initialized, and waiting for start. 
    ---------------------------------------------------------------------------------
    Status START | this status start to open vdec and the dequeue is null, so it will
                 | push packet until dequeue has decoded-image data. 
    ---------------------------------------------------------------------------------
    Status RUN   | run video decoder and pull stream packet until packet is null. 
    ---------------------------------------------------------------------------------
    Status END   | end of push packet to the vdec, and pop image data until the  
                 | dequeue is null. 
    =================================================================================
    ```
    Args:
        None

    Returns:
        bool : True for VideoCapture is ready or False.
    &#34;&#34;&#34;
    if self._status == Status.START or self._status == Status.READY:
        # get one packet data
        packet = next(self.packets)

        # if packet is null, jump to status IDLE
        if packet.buffer_size &lt;= 0:
            self._status == Status.IDLE
            return False

        # construct a frame
        self._frame = self._frame + 1
        shape = (self.stream.width, self.stream.height)
        frame = Frame(packet, shape, frame_id=self._frame, context=self.context)

        # do video decode
        self.decoder.process(frame)

        # if dequeue has image data, it jump to status RUN
        if not self.decoder.image.empty():
            self._status = Status.RUN
        return True

    elif self._status == Status.RUN:
        # get one packet data
        packet = next(self.packets)
        
        # if packet is null, send eos frame and jump to status IDLE
        shape = (self.stream.width, self.stream.height)
        if packet.buffer_size &lt;= 0:
            # send eos frame
            frame = Frame(packet, shape, is_last=True, context=self.context)

            # after send eos, it jump to status END
            self._status = Status.END
        else:
            self._frame = self._frame + 1
            frame = Frame(packet, shape, frame_id=self._frame, context=self.context)

        # do video decode
        self.decoder.process(frame)
        return True

    elif self._status == Status.END:
        if self.decoder.image.empty():
            self.decoder.finish()
            self._status = Status.IDLE
            return False

        return True
    else:
        self._status = Status.IDLE
        return False</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.read"><code class="name flex">
<span>def <span class="ident">read</span></span>(<span>self, print_status=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Read one frame from caputure in device. If we cann't get the data in the timeout,
it will be raise an timeout error.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>print_status</code></strong> :&ensp;<code>bool</code>, optional</dt>
<dd>Get the queue status for True</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[<a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a>]</code></dt>
<dd>Get a decoded frame.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L299-L317" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def read(self, print_status=True):     
    &#34;&#34;&#34;Read one frame from caputure in device. If we cann&#39;t get the data in the timeout, 
        it will be raise an timeout error.
    Args:
        print_status (bool, optional): Get the queue status for True

    Returns:
        [AscendArray]: Get a decoded frame.
    &#34;&#34;&#34;
    if self._status != Status.IDLE and not self.decoder.image.empty():
        if print_status:
            Log(INFO, f&#34;qsize = {self.decoder.image.qsize()}.&#34;)
            print(f&#34;qsize = {self.decoder.image.qsize()}&#34;)
        frame_id, image = self.decoder.image.get(timeout=30)
        
        return image, frame_id
    else:
        Log(WARNING, &#39;read image failed in Video Capture.&#39;)
        return (None, None)</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.release"><code class="name flex">
<span>def <span class="ident">release</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Closes video file or capturing device and release resource.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L382-L391" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def release(self):
    &#34;&#34;&#34;Closes video file or capturing device and release resource.
    &#34;&#34;&#34;
    if hasattr(self, &#39;container&#39;):
        self.container.close()

    if hasattr(self, &#39;decoder&#39;):
        del self.decoder
    
    self._status = False</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.set"><code class="name flex">
<span>def <span class="ident">set</span></span>(<span>self, attr, value)</span>
</code></dt>
<dd>
<div class="desc"><p>set(attr, value) -&gt; retval
Sets a property in the VideoCapture</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>attr</code></strong> :&ensp;<code>str</code></dt>
<dd>Property from VideoCapture Properties (eg. 'width', 'fps', &hellip;)</dd>
<dt><strong><code>value</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of the property</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool </code></dt>
<dd><code>True</code> if the property is supported by the backend used by the VideoCapture instance.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L319-L350" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def set(self, attr, value):
    &#34;&#34;&#34;set(attr, value) -&gt; retval
        Sets a property in the VideoCapture
    Args:
        attr (str): Property from VideoCapture Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
        value (int): Value of the property

    Returns:
        bool : `True` if the property is supported by the backend used by the VideoCapture instance.
    &#34;&#34;&#34;
    if self._status == Status.READY:
        if attr == &#39;qsize&#39;: 
            self.decoder.queue_size = value
        elif attr == &#39;channel_id&#39;: 
            self.decoder.channel_id = value
        elif attr == &#39;ref_num&#39;: 
            self.decoder.ref_num = value
        elif attr == &#39;enc_type&#39;: 
            self.decoder.encoder_type = value
        elif attr == &#39;pix_fmt&#39;: 
            self.decoder.pic_format = value
        elif attr == &#39;bit_depth&#39;: 
            self.decoder.bit_depth = value
        elif attr == &#39;out_mode&#39;: 
            self.decoder.out_mode = value
        else:
            Log(ERROR, f&#39;attr {attr} is not support in VideoCapture.&#39;)
            return False
        return True
    else:
        Log(ERROR, f&#39;Set attr {attr} in status {self._status}.&#39;)
        raise ValueError(f&#34;Set attr {attr} in status {self._status}.&#34;)</code></pre>
</details>
</dd>
<dt id="ascend.VideoCapture.skip_frame"><code class="name flex">
<span>def <span class="ident">skip_frame</span></span>(<span>self, skip_type)</span>
</code></dt>
<dd>
<div class="desc"><p>Signal that we only want to look at frames, only work in ffmpeg.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>skip_type</code></strong> :&ensp;<code>int</code></dt>
<dd>A class of av.codec.context.SkipType</dd>
</dl>
<pre><code class="language-python">-------------------------------------------------------------------------------
SkipType Name | Flag Value | Meaning in FFmpeg                                 
--------------+------------+---------------------------------------------------
NONE          | 0x-10      | Discard nothing                                   
DEFAULT       | 0x0        | Discard useless packets like 0 size packets in AVI
NONREF        | 0x8        | Discard all non reference                         
BIDIR         | 0x10       | Discard all bidirectional frames                  
NONINTRA      | 0x18       | Discard all non intra frames                      
NONKEY        | 0x20       | Discard all frames except keyframes               
ALL           | 0x30       | Discard all                                       
-------------------------------------------------------------------------------
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_capture.py#L191-L216" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def skip_frame(self, skip_type):
    &#34;&#34;&#34;Signal that we only want to look at frames, only work in ffmpeg.
    Args:
        skip_type (int): A class of av.codec.context.SkipType

    ```python
    -------------------------------------------------------------------------------
    SkipType Name | Flag Value | Meaning in FFmpeg                                 
    --------------+------------+---------------------------------------------------
    NONE          | 0x-10      | Discard nothing                                   
    DEFAULT       | 0x0        | Discard useless packets like 0 size packets in AVI
    NONREF        | 0x8        | Discard all non reference                         
    BIDIR         | 0x10       | Discard all bidirectional frames                  
    NONINTRA      | 0x18       | Discard all non intra frames                      
    NONKEY        | 0x20       | Discard all frames except keyframes               
    ALL           | 0x30       | Discard all                                       
    -------------------------------------------------------------------------------
    ```
    &#34;&#34;&#34;
    if not isinstance(skip_type, str):
        raise TypeError(f&#34;Input skip_type expect a string, but got {type(skip_type)}.&#34;)

    if skip_type in [&#39;NONE&#39;, &#39;DEFAULT&#39;, &#39;NONREF&#39;, &#39;BIDIR&#39;, &#39;NONINTRA&#39;, &#39;NONKEY&#39;, &#39;ALL&#39;]:
        self.stream.codec_context.skip_frame = skip_type
    else:
        Log(WARNING, &#39;skip_frame set value failed in Video Capture.&#39;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.VideoWriter"><code class="flex name class">
<span>class <span class="ident">VideoWriter</span></span>
<span>(</span><span>context, filename, fps, frameSize, is_color=False)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a VideoWriter class to encode video stream with format h264/265.</p>
<h2 id="attributes">Attributes</h2>
<dl>
<dt><strong><code>encode</code></strong> :&ensp;<code><a title="ascend.Venc" href="#ascend.Venc">Venc</a> obj</code></dt>
<dd>The DVPP video encoder object.</dd>
<dt><strong><code>fps</code></strong> :&ensp;<code>int</code></dt>
<dd>frame per second</dd>
<dt><strong><code>frameSize</code></strong> :&ensp;<code>tuple</code></dt>
<dd>frame shape to be encoded, like (w,h).</dd>
<dt><strong><code>width</code></strong> :&ensp;<code>int</code></dt>
<dd>Width of the frames in the video stream</dd>
<dt><strong><code>height</code></strong> :&ensp;<code>int</code></dt>
<dd>Height of the frames in the video stream.</dd>
<dt><strong><code>frames</code></strong> :&ensp;<code>int</code></dt>
<dd>Number of frames in the video file.</dd>
<dt><strong><code>format</code></strong> :&ensp;<code>int</code></dt>
<dd>video stream format</dd>
<dt><strong><code>fps</code></strong> :&ensp;<code>float</code></dt>
<dd>Frame rate.</dd>
<dt><strong><code>bitrate</code></strong> :&ensp;<code>int</code></dt>
<dd>(read-only) Video bitrate in kbits/s</dd>
<dt><strong><code>pix_fmt</code></strong> :&ensp;<code>int</code></dt>
<dd>the encode frame's pixel format, only support yuv420 NV21/12</dd>
</dl>
<h2 id="methods">Methods</h2>
<ul>
<li>write
: Writes the next video frame</li>
<li>set
: Sets a property in the VideoWriter</li>
<li>get
: Returns the specified VideoWriter property</li>
<li>release : Closes and release video writer's resource</li>
</ul></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L35-L237" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class VideoWriter():
    &#34;&#34;&#34;Define a VideoWriter class to encode video stream with format h264/265.

    Attributes:
        encode (Venc obj): The DVPP video encoder object.
        fps (int): frame per second
        frameSize (tuple): frame shape to be encoded, like (w,h).
        width (int): Width of the frames in the video stream
        height (int): Height of the frames in the video stream.
        frames (int): Number of frames in the video file.
        format (int): video stream format
        fps (float): Frame rate.
        bitrate (int): (read-only) Video bitrate in kbits/s
        pix_fmt (int): the encode frame&#39;s pixel format, only support yuv420 NV21/12

    Methods:
        - write   : Writes the next video frame
        - set     : Sets a property in the VideoWriter
        - get     : Returns the specified VideoWriter property
        - release : Closes and release video writer&#39;s resource

    &#34;&#34;&#34;
    def __init__(self, context, filename, fps, frameSize, is_color=False):
        if not isinstance(context, int):
            raise TypeError(f&#34;VideoWriter input context expects an int, bug got {type(context)}.&#34;)

        if not is_filepath(filename):
            raise TypeError(f&#34;VideoWriter input filename expects an str or Path, bug got {type(filename)}.&#34;)

        if not isinstance(fps, int):
            raise TypeError(f&#34;VideoWriter input fps expects an int, bug got {type(fps)}.&#34;)

        if not isinstance(frameSize, tuple) or len(frameSize) != 2:
            raise TypeError(f&#34;VideoWriter input frameSize expects a 2-elements tuple, bug got {type(fps)}.&#34;)

        self._context = context

        # check input param ok
        self._status = Status.IDLE

        # initial encoder
        self.encode = Venc(context, filename, frameSize[0], frameSize[1])

        # configure fps
        self.encode.fps = fps

        # intial ok, and step to READY status
        self._status = Status.READY

    @property
    def width(self):
        return self.encode.width

    @width.setter
    def width(self, width):
        if self._status == Status.READY:
            self.encode.width = width
            return True
        else:
            return False

    @property
    def height(self):
        return self.encode.height

    @height.setter
    def height(self, height):
        if self._status == Status.READY:
            self.encode.height = height
            return True
        else:
            return False

    @property
    def fps(self):
        return self.encode.fps

    @fps.setter
    def fps(self, fps):
        if self._status == Status.READY:
            self.encode.fps = fps
            return True
        else:
            return False

    @property
    def pix_fmt(self):
        return self.encode.pic_format

    @pix_fmt.setter
    def pix_fmt(self, pix_fmt):
        if self._status == Status.READY:
            self.encode.pic_format = pix_fmt
            return True
        else:
            return False


    def write(self, image):
        &#34;&#34;&#34;The function/method writes the specified image to video file. It must have the same size as has
            been specified when opening the video writer.
        Args:
            image (AscendArray): The written frame. In general, color images are expected in BGR format.

        &#34;&#34;&#34;
        if self._status in [Status.READY, Status.RUN] and image:
            if not isinstance(image, AscendArray):
                self._status = Status.END
                raise TypeError(f&#34;Input image expects an AscendArray, but got {type(image)}.&#34;)

            frame = Frame(image)
            self.encode.process(frame)
            self._status = Status.RUN
            Log(INFO, &#39;write one frame to VideoWriter.&#39;)

        else:
            Log(WARNING, f&#39;write image in status {self._status}.&#39;)

    def set(self, attr, value):
        &#34;&#34;&#34; set(attr, value) -&gt; retval
            Sets a property in the VideoWriter
        Args:
            attr (str): Property from VideoWriter Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
            value (int): Value of the property

        Returns:
            bool : `True` if the property is supported by the backend used by the VideoWriter instance.
        &#34;&#34;&#34;
        if self._status == Status.READY:
            if attr == &#39;width&#39;: 
                self.encode.width = value
            elif attr == &#39;height&#39;: 
                self.encode.height = value
            elif attr == &#39;fps&#39;: 
                self.encode.fps = value
            elif attr == &#39;enc_type&#39;: 
                self.encode.encoder_type = value
            elif attr == &#39;pix_fmt&#39;: 
                self.encode.pic_format = value
            elif attr == &#39;bit_rate&#39;: 
                self.encode.bit_rate = value
            elif attr == &#39;key_frame&#39;: 
                self.encode.frame_itval = value
            elif attr == &#39;rc_mode&#39;: 
                self.encode.rc_mode = value
            else:
                Log(ERROR, f&#39;attr {attr} is not support in VideoWriter.&#39;)
                return False
            return True
        else:
            Log(ERROR, f&#39;Set attr {attr} in status {self._status}.&#39;)
            raise ValueError(f&#34;Set attr {attr} in status {self._status}.&#34;)

    def get(self, attr):
        &#34;&#34;&#34; get(attr) -&gt; retval
            Returns the specified VideoWriter property
        Args:
            attr (str): Property from VideoWriter Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
            
        Returns:
            [int]: Value for the specified property. Value 0 is returned when querying a 
                property that is not supported by the backend used by the VideoWriter instance.
        &#34;&#34;&#34;
        if not isinstance(attr, str):
            raise TypeError(f&#34;Input attr expects a string, but got {type(attr)}.&#34;)
        
        attr_dict = {
            &#39;width&#39;       : self.encode.width,
            &#39;height&#39;      : self.encode.height,
            &#39;fps&#39;         : self.encode.fps,
            &#39;enc_type&#39;    : self.encode.encoder_type,
            &#39;pix_fmt&#39;     : self.encode.pic_format,
            &#39;bit_rate&#39;    : self.encode.bit_rate,
            &#39;key_frame&#39;   : self.encode.frame_itval,
            &#39;rc_mode&#39;     : self.encode.rc_mode
        }

        try:
            return attr_dict[attr]
        except KeyError:
            return 

    def release(self):
        &#34;&#34;&#34;Closes video file or writer and release resource.
        &#34;&#34;&#34;
        if self._status == Status.RUN:
            frame = Frame(None, is_last=True)
            self.encode.process(frame)
            self._status = Status.END

            # do finish job and stop encoder thread
            self.encode.finish()

            Log(INFO, f&#34;write last frame to VideoWriter.&#34;)

        if hasattr(self, &#39;encode&#39;):
            del self.encode
        
        self._status = Status.END

    def __del__(self):
        if hasattr(self, &#39;encode&#39;):
            del self.encode</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.VideoWriter.fps"><code class="name">var <span class="ident">fps</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L108-L110" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def fps(self):
    return self.encode.fps</code></pre>
</details>
</dd>
<dt id="ascend.VideoWriter.height"><code class="name">var <span class="ident">height</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L96-L98" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def height(self):
    return self.encode.height</code></pre>
</details>
</dd>
<dt id="ascend.VideoWriter.pix_fmt"><code class="name">var <span class="ident">pix_fmt</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L120-L122" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def pix_fmt(self):
    return self.encode.pic_format</code></pre>
</details>
</dd>
<dt id="ascend.VideoWriter.width"><code class="name">var <span class="ident">width</span></code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L84-L86" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def width(self):
    return self.encode.width</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.VideoWriter.get"><code class="name flex">
<span>def <span class="ident">get</span></span>(<span>self, attr)</span>
</code></dt>
<dd>
<div class="desc"><p>get(attr) -&gt; retval
Returns the specified VideoWriter property</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>attr</code></strong> :&ensp;<code>str</code></dt>
<dd>Property from VideoWriter Properties (eg. 'width', 'fps', &hellip;)</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>[int]</code></dt>
<dd>Value for the specified property. Value 0 is returned when querying a
property that is not supported by the backend used by the VideoWriter instance.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L188-L215" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def get(self, attr):
    &#34;&#34;&#34; get(attr) -&gt; retval
        Returns the specified VideoWriter property
    Args:
        attr (str): Property from VideoWriter Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
        
    Returns:
        [int]: Value for the specified property. Value 0 is returned when querying a 
            property that is not supported by the backend used by the VideoWriter instance.
    &#34;&#34;&#34;
    if not isinstance(attr, str):
        raise TypeError(f&#34;Input attr expects a string, but got {type(attr)}.&#34;)
    
    attr_dict = {
        &#39;width&#39;       : self.encode.width,
        &#39;height&#39;      : self.encode.height,
        &#39;fps&#39;         : self.encode.fps,
        &#39;enc_type&#39;    : self.encode.encoder_type,
        &#39;pix_fmt&#39;     : self.encode.pic_format,
        &#39;bit_rate&#39;    : self.encode.bit_rate,
        &#39;key_frame&#39;   : self.encode.frame_itval,
        &#39;rc_mode&#39;     : self.encode.rc_mode
    }

    try:
        return attr_dict[attr]
    except KeyError:
        return </code></pre>
</details>
</dd>
<dt id="ascend.VideoWriter.release"><code class="name flex">
<span>def <span class="ident">release</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>Closes video file or writer and release resource.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L217-L233" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def release(self):
    &#34;&#34;&#34;Closes video file or writer and release resource.
    &#34;&#34;&#34;
    if self._status == Status.RUN:
        frame = Frame(None, is_last=True)
        self.encode.process(frame)
        self._status = Status.END

        # do finish job and stop encoder thread
        self.encode.finish()

        Log(INFO, f&#34;write last frame to VideoWriter.&#34;)

    if hasattr(self, &#39;encode&#39;):
        del self.encode
    
    self._status = Status.END</code></pre>
</details>
</dd>
<dt id="ascend.VideoWriter.set"><code class="name flex">
<span>def <span class="ident">set</span></span>(<span>self, attr, value)</span>
</code></dt>
<dd>
<div class="desc"><p>set(attr, value) -&gt; retval
Sets a property in the VideoWriter</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>attr</code></strong> :&ensp;<code>str</code></dt>
<dd>Property from VideoWriter Properties (eg. 'width', 'fps', &hellip;)</dd>
<dt><strong><code>value</code></strong> :&ensp;<code>int</code></dt>
<dd>Value of the property</dd>
</dl>
<h2 id="returns">Returns</h2>
<dl>
<dt><code>bool </code></dt>
<dd><code>True</code> if the property is supported by the backend used by the VideoWriter instance.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L153-L186" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def set(self, attr, value):
    &#34;&#34;&#34; set(attr, value) -&gt; retval
        Sets a property in the VideoWriter
    Args:
        attr (str): Property from VideoWriter Properties (eg. &#39;width&#39;, &#39;fps&#39;, ...)
        value (int): Value of the property

    Returns:
        bool : `True` if the property is supported by the backend used by the VideoWriter instance.
    &#34;&#34;&#34;
    if self._status == Status.READY:
        if attr == &#39;width&#39;: 
            self.encode.width = value
        elif attr == &#39;height&#39;: 
            self.encode.height = value
        elif attr == &#39;fps&#39;: 
            self.encode.fps = value
        elif attr == &#39;enc_type&#39;: 
            self.encode.encoder_type = value
        elif attr == &#39;pix_fmt&#39;: 
            self.encode.pic_format = value
        elif attr == &#39;bit_rate&#39;: 
            self.encode.bit_rate = value
        elif attr == &#39;key_frame&#39;: 
            self.encode.frame_itval = value
        elif attr == &#39;rc_mode&#39;: 
            self.encode.rc_mode = value
        else:
            Log(ERROR, f&#39;attr {attr} is not support in VideoWriter.&#39;)
            return False
        return True
    else:
        Log(ERROR, f&#39;Set attr {attr} in status {self._status}.&#39;)
        raise ValueError(f&#34;Set attr {attr} in status {self._status}.&#34;)</code></pre>
</details>
</dd>
<dt id="ascend.VideoWriter.write"><code class="name flex">
<span>def <span class="ident">write</span></span>(<span>self, image)</span>
</code></dt>
<dd>
<div class="desc"><p>The function/method writes the specified image to video file. It must have the same size as has
been specified when opening the video writer.</p>
<h2 id="args">Args</h2>
<dl>
<dt><strong><code>image</code></strong> :&ensp;<code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></dt>
<dd>The written frame. In general, color images are expected in BGR format.</dd>
</dl></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/video/video_writer.py#L133-L151" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def write(self, image):
    &#34;&#34;&#34;The function/method writes the specified image to video file. It must have the same size as has
        been specified when opening the video writer.
    Args:
        image (AscendArray): The written frame. In general, color images are expected in BGR format.

    &#34;&#34;&#34;
    if self._status in [Status.READY, Status.RUN] and image:
        if not isinstance(image, AscendArray):
            self._status = Status.END
            raise TypeError(f&#34;Input image expects an AscendArray, but got {type(image)}.&#34;)

        frame = Frame(image)
        self.encode.process(frame)
        self._status = Status.RUN
        Log(INFO, &#39;write one frame to VideoWriter.&#39;)

    else:
        Log(WARNING, f&#39;write image in status {self._status}.&#39;)</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="ascend.Vmul"><code class="flex name class">
<span>class <span class="ident">Vmul</span></span>
<span>(</span><span>context, mat_a, vec_x, vec_y, alpha=1.0, beta=0.0, highprec=True)</span>
</code></dt>
<dd>
<div class="desc"><p>Define a vector multiply object, release the function .</p>
<p>Attributes::
context (int): the output image bind with an AscendArray object, image.shape(tupe(h, w, c))
stream (int): The stream resource of this operator
highprec (bool): Precious mode</p>
<h2 id="methods">Methods</h2>
<p>run
: do compute matmul
out
: return output result</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L190-L339" class="git-link">Browse git</a>
</summary>
<pre><code class="python">class Vmul():
    &#34;&#34;&#34;Define a vector multiply object, release the function .

    Attributes::
        context (int): the output image bind with an AscendArray object, image.shape(tupe(h, w, c))
        stream (int): The stream resource of this operator
        highprec (bool): Precious mode

    Methods:
        run           : do compute matmul
        out           : return output result
    &#34;&#34;&#34;
    def __init__(self, context, mat_a, vec_x, vec_y, alpha=1.0, beta=0.0, highprec=True):
        if not isinstance(context, int):
            raise TypeError(f&#34;Input context expects an int, but got {type(context)}.&#34;)

        if not isinstance(mat_a, AscendArray):
            raise TypeError(f&#34;Input mat_a expects an AscendArray, but got {type(mat_a)}.&#34;)

        if not isinstance(vec_x, AscendArray):
            raise TypeError(f&#34;Input vec_x expects an AscendArray, but got {type(vec_x)}.&#34;)

        if not isinstance(vec_y, AscendArray):
            raise TypeError(f&#34;Input vec_y expects an AscendArray, but got {type(vec_y)}.&#34;)

        assert mat_a.format == vec_x.format, f&#34;Input mat_a and vec_x expects same format.&#34;

        # assign self value
        self.context = context
        self.stream = create_stream(context)
        self.highprec = 1 if highprec else 0

        # set op model dir
        ret = acl.op.set_model_dir(&#34;op_models&#34;)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;op set model dir failed, return {ret}.&#34;)
        
        # calculate m, n, k and trans alpha and beta to np.ndarray
        self.__pre_compute(mat_a, vec_x, vec_y, alpha, beta)

        # do blas gemm_ex and synchronize stream
        self.run()

        # free input data memory
        self.free_in()


    def __pre_compute(self, mat_a, vec_x, vec_y, alpha, beta):
        &#34;&#34;&#34;Calculate m, n, k and copy alpha/beta to device.
        Args:
            mat_a : (AscendArray) matrix A
            vec_x : (AscendArray) vector x
            vec_y : (AscendArray) vector y
            alpha : (float value)
            beta  : (float value)

        Returns:
            None
        &#34;&#34;&#34;
        if mat_a.format in [
            PIXEL_FORMAT_YUV_SEMIPLANAR_420,
            PIXEL_FORMAT_YVU_SEMIPLANAR_420
            ]:
            self.m = mat_a.shape[-1]
            self.n = mat_a.shape[0] * 2 // 3
            self.k = vec_x.shape[1] * 2 // 3
        elif mat_a.format in [
            PIXEL_FORMAT_YUV_SEMIPLANAR_422,
            PIXEL_FORMAT_YVU_SEMIPLANAR_422
            ]:
            self.m = mat_a.shape[-1]
            self.n = mat_a.shape[0] * 2 // 3
            self.k = vec_y.shape[1] * 2 // 3
        elif mat_a.format == &#39;NCHW&#39;:
            self.m = mat_a.shape[-1]
            self.n = mat_a.shape[0]
            self.k = mat_b.shape[1]
        elif mat_a.format == &#39;NHWC&#39;:
            self.m = mat_a.shape[-1]
            self.n = mat_a.shape[0]
            self.k = mat_b.shape[1]
        else:
            raise ValueError(f&#34;Input data format not support.&#34;)

        alpha = np.array([alpha]).astype(mat_a.dtype)
        beta  = np.array([beta]).astype(mat_a.dtype)
        self.alpha = AscendArray.clone(alpha)
        self.beta = AscendArray.clone(beta)

    def run(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        a_type = type_map(self.mat_a.dtype)
        x_type = type_map(self.vec_x.dtype)
        y_type = type_map(self.vec_y.dtype)
        # do vmul asyncronize
        ret = acl.blas.gemv_ex(ACL_TRANS_N, 
                                self.m, self.n,
                                self.alpha.ascend_data, 
                                self.mat_a.ascend_data, self.k, a_type, 
                                self.vec_x.ascend_data, incx, x_type, 
                                self.beta.ascend_data, 
                                self.vec_y.ascend_data, incy, y_type, 
                                self.high_prec,
                                self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to do blas gemv_ex, return {ret}.&#34;)

        # do synchronize stream 
        ret = acl.rt.synchronize_stream(self.stream)
        if ret != ACL_SUCCESS:
            raise ValueError(f&#34;Failed to synchronize stream in running blas gemv_ex, return {ret}.&#34;)
    
    @property
    def out(self):
        &#34;&#34;&#34; run op.
        Args:
            None

        Returns:
            vec_y
        &#34;&#34;&#34;
        return self.vec_y

    def _free_ab(self):
        &#34;&#34;&#34; free alpha and beta data memory
        Args:
            None

        Returns:
            None
        &#34;&#34;&#34;
        if hasattr(self, &#39;alpha&#39;):
            del self.alpha

        if hasattr(self, &#39;beta&#39;):
            del self.beta

    def __del__(self):
        if hasattr(self, &#39;stream&#39;):
            ret = acl.rt.destroy_stream(self.stream)
            assert ret == ACL_SUCCESS, f&#34;destroy stream failed, return {ret}.&#34;
        
        # free alpha and beta data memory
        self._free_ab()</code></pre>
</details>
<h3>Instance variables</h3>
<dl>
<dt id="ascend.Vmul.out"><code class="name">var <span class="ident">out</span></code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>vec_y</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L308-L317" class="git-link">Browse git</a>
</summary>
<pre><code class="python">@property
def out(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        vec_y
    &#34;&#34;&#34;
    return self.vec_y</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="ascend.Vmul.run"><code class="name flex">
<span>def <span class="ident">run</span></span>(<span>self)</span>
</code></dt>
<dd>
<div class="desc"><p>run op.</p>
<h2 id="args">Args</h2>
<p>None</p>
<h2 id="returns">Returns</h2>
<p>None</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
<a href="https://github.com/pdoc3/pdoc/blob/37c907488ff52b174ab602690d1166f28bded9a2/ascend/ops/blas.py#L279-L306" class="git-link">Browse git</a>
</summary>
<pre><code class="python">def run(self):
    &#34;&#34;&#34; run op.
    Args:
        None

    Returns:
        None
    &#34;&#34;&#34;
    a_type = type_map(self.mat_a.dtype)
    x_type = type_map(self.vec_x.dtype)
    y_type = type_map(self.vec_y.dtype)
    # do vmul asyncronize
    ret = acl.blas.gemv_ex(ACL_TRANS_N, 
                            self.m, self.n,
                            self.alpha.ascend_data, 
                            self.mat_a.ascend_data, self.k, a_type, 
                            self.vec_x.ascend_data, incx, x_type, 
                            self.beta.ascend_data, 
                            self.vec_y.ascend_data, incy, y_type, 
                            self.high_prec,
                            self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to do blas gemv_ex, return {ret}.&#34;)

    # do synchronize stream 
    ret = acl.rt.synchronize_stream(self.stream)
    if ret != ACL_SUCCESS:
        raise ValueError(f&#34;Failed to synchronize stream in running blas gemv_ex, return {ret}.&#34;)</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<header>
<a class="homelink" rel="home" title="ascendfly Home" href="https://gitee.com/ascend-fae/ascendfly">
<img src="https://bazige.github.io/ascend/logo/logo.png" alt=""> ascendfly
</a>
</header>
<div class="gcse-search" style="height: 70px"
data-as_oq="site:bazige.github.io inurl:github.com/ascendfly"
data-gaCategoryParameter="ascend">
</div>
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3><a href="#header-submodules">Sub-modules</a></h3>
<ul>
<li><code><a title="ascend.common" href="common/index.html">ascend.common</a></code></li>
<li><code><a title="ascend.data" href="data/index.html">ascend.data</a></code></li>
<li><code><a title="ascend.image" href="image/index.html">ascend.image</a></code></li>
<li><code><a title="ascend.model" href="model/index.html">ascend.model</a></code></li>
<li><code><a title="ascend.ops" href="ops/index.html">ascend.ops</a></code></li>
<li><code><a title="ascend.post_process" href="post_process/index.html">ascend.post_process</a></code></li>
<li><code><a title="ascend.profiling" href="profiling/index.html">ascend.profiling</a></code></li>
<li><code><a title="ascend.resource" href="resource/index.html">ascend.resource</a></code></li>
<li><code><a title="ascend.video" href="video/index.html">ascend.video</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="ascend.acl_vesion" href="#ascend.acl_vesion">acl_vesion</a></code></li>
<li><code><a title="ascend.bbox_overlaps" href="#ascend.bbox_overlaps">bbox_overlaps</a></code></li>
<li><code><a title="ascend.bgr2ycbcr" href="#ascend.bgr2ycbcr">bgr2ycbcr</a></code></li>
<li><code><a title="ascend.bind_context" href="#ascend.bind_context">bind_context</a></code></li>
<li><code><a title="ascend.check_file_exist" href="#ascend.check_file_exist">check_file_exist</a></code></li>
<li><code><a title="ascend.cityscapes_classes" href="#ascend.cityscapes_classes">cityscapes_classes</a></code></li>
<li><code><a title="ascend.coco_classes" href="#ascend.coco_classes">coco_classes</a></code></li>
<li><code><a title="ascend.color_gen" href="#ascend.color_gen">color_gen</a></code></li>
<li><code><a title="ascend.color_val" href="#ascend.color_val">color_val</a></code></li>
<li><code><a title="ascend.create_stream" href="#ascend.create_stream">create_stream</a></code></li>
<li><code><a title="ascend.device_num" href="#ascend.device_num">device_num</a></code></li>
<li><code><a title="ascend.draw_bboxes" href="#ascend.draw_bboxes">draw_bboxes</a></code></li>
<li><code><a title="ascend.get_classes" href="#ascend.get_classes">get_classes</a></code></li>
<li><code><a title="ascend.imagenet_det_classes" href="#ascend.imagenet_det_classes">imagenet_det_classes</a></code></li>
<li><code><a title="ascend.imagenet_vid_classes" href="#ascend.imagenet_vid_classes">imagenet_vid_classes</a></code></li>
<li><code><a title="ascend.imgs2tensor" href="#ascend.imgs2tensor">imgs2tensor</a></code></li>
<li><code><a title="ascend.imshow" href="#ascend.imshow">imshow</a></code></li>
<li><code><a title="ascend.imshow_bboxes" href="#ascend.imshow_bboxes">imshow_bboxes</a></code></li>
<li><code><a title="ascend.imshow_bboxes_colors" href="#ascend.imshow_bboxes_colors">imshow_bboxes_colors</a></code></li>
<li><code><a title="ascend.imshow_det_bboxes" href="#ascend.imshow_det_bboxes">imshow_det_bboxes</a></code></li>
<li><code><a title="ascend.is_filepath" href="#ascend.is_filepath">is_filepath</a></code></li>
<li><code><a title="ascend.mkdir_or_exist" href="#ascend.mkdir_or_exist">mkdir_or_exist</a></code></li>
<li><code><a title="ascend.nms" href="#ascend.nms">nms</a></code></li>
<li><code><a title="ascend.rgb2ycbcr" href="#ascend.rgb2ycbcr">rgb2ycbcr</a></code></li>
<li><code><a title="ascend.run_mode" href="#ascend.run_mode">run_mode</a></code></li>
<li><code><a title="ascend.show_bbox" href="#ascend.show_bbox">show_bbox</a></code></li>
<li><code><a title="ascend.show_growth" href="#ascend.show_growth">show_growth</a></code></li>
<li><code><a title="ascend.show_img" href="#ascend.show_img">show_img</a></code></li>
<li><code><a title="ascend.show_tensor" href="#ascend.show_tensor">show_tensor</a></code></li>
<li><code><a title="ascend.tensor2imgs" href="#ascend.tensor2imgs">tensor2imgs</a></code></li>
<li><code><a title="ascend.voc_classes" href="#ascend.voc_classes">voc_classes</a></code></li>
<li><code><a title="ascend.wider_face_classes" href="#ascend.wider_face_classes">wider_face_classes</a></code></li>
<li><code><a title="ascend.ycbcr2bgr" href="#ascend.ycbcr2bgr">ycbcr2bgr</a></code></li>
<li><code><a title="ascend.ycbcr2rgb" href="#ascend.ycbcr2rgb">ycbcr2rgb</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="ascend.ArgMax" href="#ascend.ArgMax">ArgMax</a></code></h4>
<ul class="">
<li><code><a title="ascend.ArgMax.data" href="#ascend.ArgMax.data">data</a></code></li>
<li><code><a title="ascend.ArgMax.run" href="#ascend.ArgMax.run">run</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.AscendArray" href="#ascend.AscendArray">AscendArray</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.AscendArray.ascend_data" href="#ascend.AscendArray.ascend_data">ascend_data</a></code></li>
<li><code><a title="ascend.AscendArray.astype" href="#ascend.AscendArray.astype">astype</a></code></li>
<li><code><a title="ascend.AscendArray.clone" href="#ascend.AscendArray.clone">clone</a></code></li>
<li><code><a title="ascend.AscendArray.context" href="#ascend.AscendArray.context">context</a></code></li>
<li><code><a title="ascend.AscendArray.dtype" href="#ascend.AscendArray.dtype">dtype</a></code></li>
<li><code><a title="ascend.AscendArray.flag" href="#ascend.AscendArray.flag">flag</a></code></li>
<li><code><a title="ascend.AscendArray.format" href="#ascend.AscendArray.format">format</a></code></li>
<li><code><a title="ascend.AscendArray.itemsize" href="#ascend.AscendArray.itemsize">itemsize</a></code></li>
<li><code><a title="ascend.AscendArray.nbytes" href="#ascend.AscendArray.nbytes">nbytes</a></code></li>
<li><code><a title="ascend.AscendArray.ndim" href="#ascend.AscendArray.ndim">ndim</a></code></li>
<li><code><a title="ascend.AscendArray.reshape" href="#ascend.AscendArray.reshape">reshape</a></code></li>
<li><code><a title="ascend.AscendArray.resize" href="#ascend.AscendArray.resize">resize</a></code></li>
<li><code><a title="ascend.AscendArray.shape" href="#ascend.AscendArray.shape">shape</a></code></li>
<li><code><a title="ascend.AscendArray.size" href="#ascend.AscendArray.size">size</a></code></li>
<li><code><a title="ascend.AscendArray.to" href="#ascend.AscendArray.to">to</a></code></li>
<li><code><a title="ascend.AscendArray.to_ascend" href="#ascend.AscendArray.to_ascend">to_ascend</a></code></li>
<li><code><a title="ascend.AscendArray.to_np" href="#ascend.AscendArray.to_np">to_np</a></code></li>
<li><code><a title="ascend.AscendArray.to_numpy" href="#ascend.AscendArray.to_numpy">to_numpy</a></code></li>
<li><code><a title="ascend.AscendArray.transpose" href="#ascend.AscendArray.transpose">transpose</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.AscendModel" href="#ascend.AscendModel">AscendModel</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.AscendModel.feed_data" href="#ascend.AscendModel.feed_data">feed_data</a></code></li>
<li><code><a title="ascend.AscendModel.get_tensor_by_name" href="#ascend.AscendModel.get_tensor_by_name">get_tensor_by_name</a></code></li>
<li><code><a title="ascend.AscendModel.run" href="#ascend.AscendModel.run">run</a></code></li>
<li><code><a title="ascend.AscendModel.set_batch" href="#ascend.AscendModel.set_batch">set_batch</a></code></li>
<li><code><a title="ascend.AscendModel.set_shape" href="#ascend.AscendModel.set_shape">set_shape</a></code></li>
<li><code><a title="ascend.AscendModel.tensor_names" href="#ascend.AscendModel.tensor_names">tensor_names</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Cast" href="#ascend.Cast">Cast</a></code></h4>
<ul class="">
<li><code><a title="ascend.Cast.data" href="#ascend.Cast.data">data</a></code></li>
<li><code><a title="ascend.Cast.run" href="#ascend.Cast.run">run</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Color" href="#ascend.Color">Color</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.Color.black" href="#ascend.Color.black">black</a></code></li>
<li><code><a title="ascend.Color.blue" href="#ascend.Color.blue">blue</a></code></li>
<li><code><a title="ascend.Color.cyan" href="#ascend.Color.cyan">cyan</a></code></li>
<li><code><a title="ascend.Color.green" href="#ascend.Color.green">green</a></code></li>
<li><code><a title="ascend.Color.magenta" href="#ascend.Color.magenta">magenta</a></code></li>
<li><code><a title="ascend.Color.red" href="#ascend.Color.red">red</a></code></li>
<li><code><a title="ascend.Color.white" href="#ascend.Color.white">white</a></code></li>
<li><code><a title="ascend.Color.yellow" href="#ascend.Color.yellow">yellow</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Context" href="#ascend.Context">Context</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.Context.bind_device" href="#ascend.Context.bind_device">bind_device</a></code></li>
<li><code><a title="ascend.Context.context_add" href="#ascend.Context.context_add">context_add</a></code></li>
<li><code><a title="ascend.Context.current_context" href="#ascend.Context.current_context">current_context</a></code></li>
<li><code><a title="ascend.Context.device_available" href="#ascend.Context.device_available">device_available</a></code></li>
<li><code><a title="ascend.Context.runmode" href="#ascend.Context.runmode">runmode</a></code></li>
<li><code><a title="ascend.Context.stream_add" href="#ascend.Context.stream_add">stream_add</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Image" href="#ascend.Image">Image</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.Image.bbox_resize" href="#ascend.Image.bbox_resize">bbox_resize</a></code></li>
<li><code><a title="ascend.Image.imcrop" href="#ascend.Image.imcrop">imcrop</a></code></li>
<li><code><a title="ascend.Image.imcrop_paste" href="#ascend.Image.imcrop_paste">imcrop_paste</a></code></li>
<li><code><a title="ascend.Image.imdecode" href="#ascend.Image.imdecode">imdecode</a></code></li>
<li><code><a title="ascend.Image.imencode" href="#ascend.Image.imencode">imencode</a></code></li>
<li><code><a title="ascend.Image.imflip" href="#ascend.Image.imflip">imflip</a></code></li>
<li><code><a title="ascend.Image.impad" href="#ascend.Image.impad">impad</a></code></li>
<li><code><a title="ascend.Image.imread" href="#ascend.Image.imread">imread</a></code></li>
<li><code><a title="ascend.Image.imrescale" href="#ascend.Image.imrescale">imrescale</a></code></li>
<li><code><a title="ascend.Image.imresize" href="#ascend.Image.imresize">imresize</a></code></li>
<li><code><a title="ascend.Image.imrotate" href="#ascend.Image.imrotate">imrotate</a></code></li>
<li><code><a title="ascend.Image.imwrite" href="#ascend.Image.imwrite">imwrite</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Matmul" href="#ascend.Matmul">Matmul</a></code></h4>
<ul class="">
<li><code><a title="ascend.Matmul.free_ab" href="#ascend.Matmul.free_ab">free_ab</a></code></li>
<li><code><a title="ascend.Matmul.out" href="#ascend.Matmul.out">out</a></code></li>
<li><code><a title="ascend.Matmul.run" href="#ascend.Matmul.run">run</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Memory" href="#ascend.Memory">Memory</a></code></h4>
<ul class="">
<li><code><a title="ascend.Memory.mem_info" href="#ascend.Memory.mem_info">mem_info</a></code></li>
<li><code><a title="ascend.Memory.reset" href="#ascend.Memory.reset">reset</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Permute" href="#ascend.Permute">Permute</a></code></h4>
<ul class="">
<li><code><a title="ascend.Permute.data" href="#ascend.Permute.data">data</a></code></li>
<li><code><a title="ascend.Permute.run" href="#ascend.Permute.run">run</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Profiling" href="#ascend.Profiling">Profiling</a></code></h4>
<ul class="">
<li><code><a title="ascend.Profiling.elapse_time" href="#ascend.Profiling.elapse_time">elapse_time</a></code></li>
<li><code><a title="ascend.Profiling.info_print" href="#ascend.Profiling.info_print">info_print</a></code></li>
<li><code><a title="ascend.Profiling.profiling" href="#ascend.Profiling.profiling">profiling</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Transpose" href="#ascend.Transpose">Transpose</a></code></h4>
<ul class="">
<li><code><a title="ascend.Transpose.data" href="#ascend.Transpose.data">data</a></code></li>
<li><code><a title="ascend.Transpose.run" href="#ascend.Transpose.run">run</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Vdec" href="#ascend.Vdec">Vdec</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.Vdec.bit_depth" href="#ascend.Vdec.bit_depth">bit_depth</a></code></li>
<li><code><a title="ascend.Vdec.channel_id" href="#ascend.Vdec.channel_id">channel_id</a></code></li>
<li><code><a title="ascend.Vdec.encoder_type" href="#ascend.Vdec.encoder_type">encoder_type</a></code></li>
<li><code><a title="ascend.Vdec.finish" href="#ascend.Vdec.finish">finish</a></code></li>
<li><code><a title="ascend.Vdec.out_mode" href="#ascend.Vdec.out_mode">out_mode</a></code></li>
<li><code><a title="ascend.Vdec.pic_format" href="#ascend.Vdec.pic_format">pic_format</a></code></li>
<li><code><a title="ascend.Vdec.process" href="#ascend.Vdec.process">process</a></code></li>
<li><code><a title="ascend.Vdec.queue_size" href="#ascend.Vdec.queue_size">queue_size</a></code></li>
<li><code><a title="ascend.Vdec.ref_num" href="#ascend.Vdec.ref_num">ref_num</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Venc" href="#ascend.Venc">Venc</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.Venc.bit_rate" href="#ascend.Venc.bit_rate">bit_rate</a></code></li>
<li><code><a title="ascend.Venc.encoder_type" href="#ascend.Venc.encoder_type">encoder_type</a></code></li>
<li><code><a title="ascend.Venc.finish" href="#ascend.Venc.finish">finish</a></code></li>
<li><code><a title="ascend.Venc.fps" href="#ascend.Venc.fps">fps</a></code></li>
<li><code><a title="ascend.Venc.frame_itval" href="#ascend.Venc.frame_itval">frame_itval</a></code></li>
<li><code><a title="ascend.Venc.height" href="#ascend.Venc.height">height</a></code></li>
<li><code><a title="ascend.Venc.pic_format" href="#ascend.Venc.pic_format">pic_format</a></code></li>
<li><code><a title="ascend.Venc.process" href="#ascend.Venc.process">process</a></code></li>
<li><code><a title="ascend.Venc.rc_mode" href="#ascend.Venc.rc_mode">rc_mode</a></code></li>
<li><code><a title="ascend.Venc.width" href="#ascend.Venc.width">width</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.VideoCapture" href="#ascend.VideoCapture">VideoCapture</a></code></h4>
<ul class="">
<li><code><a title="ascend.VideoCapture.coded_height" href="#ascend.VideoCapture.coded_height">coded_height</a></code></li>
<li><code><a title="ascend.VideoCapture.coded_width" href="#ascend.VideoCapture.coded_width">coded_width</a></code></li>
<li><code><a title="ascend.VideoCapture.display_aspect_ratio" href="#ascend.VideoCapture.display_aspect_ratio">display_aspect_ratio</a></code></li>
<li><code><a title="ascend.VideoCapture.format" href="#ascend.VideoCapture.format">format</a></code></li>
<li><code><a title="ascend.VideoCapture.fps" href="#ascend.VideoCapture.fps">fps</a></code></li>
<li><code><a title="ascend.VideoCapture.framerate" href="#ascend.VideoCapture.framerate">framerate</a></code></li>
<li><code><a title="ascend.VideoCapture.frames" href="#ascend.VideoCapture.frames">frames</a></code></li>
<li><code><a title="ascend.VideoCapture.get" href="#ascend.VideoCapture.get">get</a></code></li>
<li><code><a title="ascend.VideoCapture.has_b_frames" href="#ascend.VideoCapture.has_b_frames">has_b_frames</a></code></li>
<li><code><a title="ascend.VideoCapture.height" href="#ascend.VideoCapture.height">height</a></code></li>
<li><code><a title="ascend.VideoCapture.is_open" href="#ascend.VideoCapture.is_open">is_open</a></code></li>
<li><code><a title="ascend.VideoCapture.pix_fmt" href="#ascend.VideoCapture.pix_fmt">pix_fmt</a></code></li>
<li><code><a title="ascend.VideoCapture.read" href="#ascend.VideoCapture.read">read</a></code></li>
<li><code><a title="ascend.VideoCapture.release" href="#ascend.VideoCapture.release">release</a></code></li>
<li><code><a title="ascend.VideoCapture.set" href="#ascend.VideoCapture.set">set</a></code></li>
<li><code><a title="ascend.VideoCapture.skip_frame" href="#ascend.VideoCapture.skip_frame">skip_frame</a></code></li>
<li><code><a title="ascend.VideoCapture.width" href="#ascend.VideoCapture.width">width</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.VideoWriter" href="#ascend.VideoWriter">VideoWriter</a></code></h4>
<ul class="two-column">
<li><code><a title="ascend.VideoWriter.fps" href="#ascend.VideoWriter.fps">fps</a></code></li>
<li><code><a title="ascend.VideoWriter.get" href="#ascend.VideoWriter.get">get</a></code></li>
<li><code><a title="ascend.VideoWriter.height" href="#ascend.VideoWriter.height">height</a></code></li>
<li><code><a title="ascend.VideoWriter.pix_fmt" href="#ascend.VideoWriter.pix_fmt">pix_fmt</a></code></li>
<li><code><a title="ascend.VideoWriter.release" href="#ascend.VideoWriter.release">release</a></code></li>
<li><code><a title="ascend.VideoWriter.set" href="#ascend.VideoWriter.set">set</a></code></li>
<li><code><a title="ascend.VideoWriter.width" href="#ascend.VideoWriter.width">width</a></code></li>
<li><code><a title="ascend.VideoWriter.write" href="#ascend.VideoWriter.write">write</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="ascend.Vmul" href="#ascend.Vmul">Vmul</a></code></h4>
<ul class="">
<li><code><a title="ascend.Vmul.out" href="#ascend.Vmul.out">out</a></code></li>
<li><code><a title="ascend.Vmul.run" href="#ascend.Vmul.run">run</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p><span style="color:#ddd">&#21328;</span></p>
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.9.2</a>.</p>
</footer>
</body>
</html>